package com.fingard.dsp.bank.directbank.cib01;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IBillPool;
import com.fingard.dsp.bank.reqrespobj.billpool.*;
import com.fingard.dsp.bank.reqrespobj.billpool.Detail.*;
import com.fingard.io.FileHelper;
import com.fingard.net.FormSubmit;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlReadMode;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import netbank.firm.service.FileService;
import org.springframework.stereotype.Component;

import java.io.File;
import java.sql.Connection;
import java.util.*;

@Component("CIB01BillPool")
public class CIB01BillPool extends CIB01Base implements IBillPool {
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,REQSEQID,BANKREQSEQID,RESERVE1) values (?,?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT RESERVE1,BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;";

    public static final String INSERTRECEIPT2 = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,BUSITYPE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?,?);";

    /**
     * 在线出票融资申请
     * @param p_reqB317
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB317OnlineFinancingApply BP901_OnlineFinancingApply(ReqB317OnlineFinancingApply p_reqB317) throws Exception {
        RetAtsB317OnlineFinancingApply retAts = new RetAtsB317OnlineFinancingApply(p_reqB317.reqHeader);
        retAts.writeStart();
        Connection conn = null;
        try {
            //拼接请求报文
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonBillPoolHeaderEn(xmlWriter);
            xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
            xmlWriter.writeStartElement("DRAWFINANCETRNRQ");
            xmlWriter.writeElementString("TRNUID", p_reqB317.clientRef);//客户端交易的唯一流水号
            xmlWriter.writeStartElement("RQBODY");
            xmlWriter.writeElementString("BIZCODE", p_reqB317.bizcode);//业务品种代码
            xmlWriter.writeElementString("CURRENCY", "01");//币种
            xmlWriter.writeElementString("FINPURPOSE", p_reqB317.finPurpose);//融资用途
            xmlWriter.writeElementString("APPLYDESC", p_reqB317.applyDesc);//申请说明
            xmlWriter.writeElementString("DRAWACCTID", p_reqB317.drawAcctid);//出票融资申请人账号
            xmlWriter.writeElementString("CRDLVL", p_reqB317.crdlvl);//出票人信用评级
            xmlWriter.writeElementString("RTGAGNCY", p_reqB317.rtgagncy);//出票人评级主体
            xmlWriter.writeElementString("RTGDUEDATE", p_reqB317.rtgduedate);//出票人评级到期日
            xmlWriter.writeElementString("TOTALCOUNT", p_reqB317.totalCount);//票据总笔数
            xmlWriter.writeElementString("TOTALAMT", p_reqB317.totalAmt);//票据总金额
            xmlWriter.writeElementString("TYPE", p_reqB317.type);//商票交易类型
            xmlWriter.writeElementString("CONFIRM", p_reqB317.confirm);//是否确认合同
            while (p_reqB317.readRecord()) {
                ReqB317OnlineFinancingApplyDetail reqDetail = p_reqB317.reqDetail;
                xmlWriter.writeStartElement("CONTENT");//票据内容循环体
                xmlWriter.writeElementString("INDX", getINDX());
                if (StringHelper.isNullOrEmpty(reqDetail.billType)) {
                    xmlWriter.writeElementString("BILLTYPE", "");//票据类型
                } else {
                    if (!"1".equals(reqDetail.billType) && !"2".equals(reqDetail.billType)) {
                        xmlWriter.writeElementString("BILLTYPE", reqDetail.billType);//票据类型
                    } else {
                        xmlWriter.writeElementString("BILLTYPE", "1".equals(reqDetail.billType) ? "AC01" : "AC02");//票据类型
                    }
                }
                xmlWriter.writeElementString("BILLAMT", reqDetail.billAmt);//票据金额
                xmlWriter.writeElementString("DRAWDATE", p_reqB317.reqDetail.drawDate);//出票日期，8位
                xmlWriter.writeElementString("DUEDATE", p_reqB317.reqDetail.dueDate);//票据到期日, 8位
                if (StringHelper.isNullOrEmpty(p_reqB317.reqDetail.negtbl)) {
                    xmlWriter.writeElementString("NEGTBL", "");//不得转让标记,4位(EM00:可再转让,EM01:不可再转让)
                } else {
                    if (!"1".equals(p_reqB317.reqDetail.negtbl) && !"0".equals(p_reqB317.reqDetail.negtbl)) {
                        xmlWriter.writeElementString("NEGTBL", p_reqB317.reqDetail.negtbl);//不得转让标记,4位(EM00:可再转让,EM01:不可再转让)
                    } else {
                        xmlWriter.writeElementString("NEGTBL", "1".equals(p_reqB317.reqDetail.negtbl) ? "EM00" : "EM01");//不得转让标记,4位(EM00:可再转让,EM01:不可再转让)
                    }
                }
                xmlWriter.writeStartElement("ACACCT");//承兑人账户信息
                xmlWriter.writeElementString("NAME", p_reqB317.reqDetail.name);//承兑人名称
                xmlWriter.writeElementString("ACCTID", p_reqB317.reqDetail.acctid);//承兑人账号
                xmlWriter.writeElementString("BANKNUM", p_reqB317.reqDetail.bankNum);//承兑人开户行号
                xmlWriter.writeEndElement();//</ACACCT>
                xmlWriter.writeStartElement("PAYEEACCT");//收款账户信息
                xmlWriter.writeElementString("NAME", p_reqB317.reqDetail.payeeName);//收款人名称
                xmlWriter.writeElementString("ACCTID", p_reqB317.reqDetail.payeeAcctid);//收款人账号
                xmlWriter.writeElementString("BANKNUM", p_reqB317.reqDetail.payeeBankNum);//收款人开户行号
                xmlWriter.writeEndElement();//</PAYEEACCT>
                xmlWriter.writeElementString("ENTRSPAY", p_reqB317.reqDetail.entrspay);//到期无条件支付委托,4位只能是CC00
                xmlWriter.writeElementString("CONTRACTID", p_reqB317.reqDetail.contractid);//合同编号
                xmlWriter.writeElementString("INVCNO", p_reqB317.reqDetail.invcno);//发票编号
                xmlWriter.writeElementString("DRAWMEMO", p_reqB317.reqDetail.drawmemo);//出票登记备注
                xmlWriter.writeEndElement();//</CONTENT>
            }
            xmlWriter.writeEndDocument();
            //拼接请求报文完成，发送至银行并获取响应结果
            String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString());
            //处理银行响应
            if (tmpRetBkStr[0].length() == 0) {
                String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                if (tmpBkReader != null) {
                    String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                    String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/SEVERITY");
                    if ("0".equals(trspcod)) {
                        String rspCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/DRAWFINANCETRNRS/STATUS/CODE");
                        String rspMesg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/DRAWFINANCETRNRS/STATUS/MESSAGE");
                        String resultCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/DRAWFINANCETRNRS/RSBODY/XFERPRCSTS/XFERPRCCODE");
                        String resultMesg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/DRAWFINANCETRNRS/RSBODY/XFERPRCSTS/MESSAGE");
                        String billSeqID = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/DRAWFINANCETRNRS/RSBODY/SRVRID");
                        retAts.respCode = "0";
                        retAts.respInfo = "处理结果：" + rspMesg + "；" + resultMesg;
                        if (!"0".equals(rspCode) && StringHelper.isNullOrEmpty(resultCode)) {
                            retAts.transState = "ERROR";
                        } else {
                            retAts.billSeqID = billSeqID;
                            if (StringHelper.isNullOrEmpty(resultCode)) {
                                retAts.transState = "INFO";
                            } else {
                                retAts.transState = resultCode;
                            }
                        }
                        retAts.payInfoCode = retAts.transState;
                        retAts.reqSeqID = p_reqB317.clientRef;
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = trspmsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpRetBkStr[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn("在线出票融资申请异常：" + e);
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        retAts.writeAfter();
        return retAts;
    }

    /**
     * 融资申请处理结果查询
     * @param p_reqB318
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB318FinancingApplyQry BP902_FinancingApplyQry(ReqB318FinancingApplyQry p_reqB318) throws Exception {
        RetAtsB318FinancingApplyQry retAts = new RetAtsB318FinancingApplyQry(p_reqB318.reqHeader);
        retAts.writeStart();
        Connection conn = null;
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonBillPoolHeaderEn(xmlWriter);
            xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
            xmlWriter.writeStartElement("QUERYDRAWFINANCETRNRQ");
            xmlWriter.writeElementString("TRNUID", p_reqB318.reqHeader.transSeqID);//客户端交易的唯一流水号
            xmlWriter.writeStartElement("RQBODY");
            xmlWriter.writeElementString("CLIENTREF", p_reqB318.clientRef);//在线融资申请使用的交易流水号
            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString());
            if (tmpRetBkStr[0].length() == 0) {
                String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                if (tmpBkReader != null) {
                    String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                    String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/SEVERITY");
                    if ("0".equals(trspcod)) {
                        String retCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINANCETRNRS/STATUS/CODE");
                        String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSV1/QUERYDRAWFINANCETRNRS/STATUS/MESSAGE");
                        if ("0".equals(retCode)) {
                            String resultCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINANCETRNRS/RSBODY/RESULTCODE");
                            String resultMsge = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINANCETRNRS/RSBODY/ERRMESSAGE");
                            //01-数据校验不通过 02-处理中 03-文件生成失败 04-文件生成成功
                            if ("04".equals(resultCode)) {
                                //下载成功生成的合同文件
                                String fileId = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINANCETRNRS/RSBODY/FILEID");
                                String fileName = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINANCETRNRS/RSBODY/FILENAME");
                                String localFilePath = "";//下载文件保存路径
                                try {
                                    //根据fileId和fileName下载文件
                                    FileService service = new FileService();
                                    localFilePath = service.downloadFile(fileName, fileId);//如果文件下载成功返回system.properties配置的本地下载文件存储绝对路径
                                    if (FileHelper.existFile(localFilePath)) {
                                        WriteBankLogLn("下载成功,文件保存路径为" + localFilePath);
                                        fileName = new File(localFilePath).getName();
                                        //记录下载成功的合同文件相关信息
                                        conn = FGBiz.getLocalDbConn();
                                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                        JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_reqB318.reqHeader.bankCode, p_reqB318.clientRef, p_reqB318.clientRef, localFilePath});
                                    } else {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "合同文件生成成功，下载文件不存在，请重新点击查询下载";
                                        retAts.writeAfter();
                                        return retAts;
                                    }
                                } catch (Exception e) {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "合同文件生成成功，下载文件异常，请重新点击查询下载，报错信息：" + e.getMessage();
                                    retAts.writeAfter();
                                    return retAts;
                                }
                                //将下载成功的合同文件上传
                                String uploadType = SmbFileUtil.getUploadType();
                                String tmpByDatePath = Format.Date8Format.format(new Date());//本地临时文件的前置路径(要在共享目录新增的文件夹路径)
                                tmpByDatePath = tmpByDatePath.substring(0, 6) + "/" + tmpByDatePath.substring(6, 8) + "/"
                                        + p_reqB318.reqHeader.bankCode + "/" + p_reqB318.drawAcctid + "/";
                                int result = -1;//-1文件上传失败 0文件上传成功 1文件已经存在
                                String AtsFilePath = "";//共享目录下存储文件的子目录
                                if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                    if ("smb".equals(uploadType)) {
                                        WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                        result = SmbFileUtil.smbUploadingInChar(localFilePath, tmpByDatePath, FGBiz.dspCenter.dspSet.receiptShareDir);
                                        AtsFilePath = tmpByDatePath + fileName;
                                    } else if ("localhost".equals(uploadType)) {
                                        //未测
                                        String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                        WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                        result = FileHelper.copyFile(localFilePath, shareDir + tmpByDatePath + fileName);
                                        AtsFilePath = tmpByDatePath + fileName;
                                    } else {
                                        //未测
                                        tmpByDatePath = tmpByDatePath.replaceAll(reqHeader.bankCode + "/", "");
                                        WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                        Map<String, String> map = FormSubmit.fileUpload(FGBiz.dspCenter.dspSet.receiptShareDir, p_reqB318.drawAcctid, localFilePath, tmpByDatePath, fileName, getCharset());
                                        WriteBankLogStep3(JSON.toJSONString(map));
                                        if (map.keySet().size() != 0) {
                                            result = Integer.valueOf(map.get("respCode"));
                                            tmpByDatePath = map.get("remotePath");
                                            AtsFilePath = tmpByDatePath;
                                        } else {
                                            result = -1;
                                        }
                                    }
                                } else {
                                    //未测
                                    //ftp服务器
                                    FtpSet ftpSet2 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                    WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet2.upDir);
                                    //上传ftp服务器的地址
                                    AtsFilePath = tmpByDatePath + fileName;
                                    String ftpFilePath = "";
                                    ftpFilePath = StringHelper.trimEndFileSp(ftpSet2.upDir) + "/" + AtsFilePath;
                                    WriteBankLogLn("开始将合同文件" + localFilePath + "上传至" + ftpFilePath);
                                    //上传至ftp
                                    result = FtpUtil.ftpUploading(ftpSet2, localFilePath, ftpFilePath);
                                }
                                if (result == 0 || result == 1) {
                                    WriteBankLogLn("合同文件上传至共享目录路径" + AtsFilePath);
                                    retAts.respCode = "0";
                                    retAts.respInfo = "合同文件已上传至共享目录";
                                    retAts.transState = retCode + "+" + resultCode;
                                    retAts.payInfoCode = retAts.transState;
                                    retAts.filePath = AtsFilePath;
                                    retAts.reqSeqID = p_reqB318.clientRef;
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "合同文件上传至共享失败，请正确配置共享目录地址后重新查询！";
                                }
                            } else {
                                retAts.respCode = "0";
                                retAts.respInfo = "返回结果：" + statusMessage + "；" + resultMsge;
                                retAts.reqSeqID = p_reqB318.clientRef;
                                retAts.transState = retCode + "+" + resultCode;//0+01 0+02 0+03（需要重新生成合同的）
                                retAts.payInfoCode = retAts.transState;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = statusMessage;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = trspmsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpRetBkStr[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn("融资申请处理结果查询异常：" + e);
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        //增加批次状态
        if ("0".equals(retAts.respCode)) {
            if ("01".equals(retAts.transState)) {
                retAts.batchState = "8";
            } else {
                retAts.batchState = "2";
            }
        }
        retAts.writeAfter();
        return retAts;
    }

    /**
     * 重新生成合同文件
     * @param p_reqB319
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB319RebuildFile BP903_RebuildFile(ReqB319RebuildFile p_reqB319) throws Exception {
        RetAtsB319RebuildFile retAts = new RetAtsB319RebuildFile(p_reqB319.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonBillPoolHeaderEn(xmlWriter);
            xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
            xmlWriter.writeStartElement("REBUILDCONTRACTTRNRQ");
            xmlWriter.writeElementString("TRNUID", p_reqB319.reqHeader.transSeqID);//客户端交易的唯一流水号
            xmlWriter.writeStartElement("RQBODY");
            xmlWriter.writeElementString("CLIENTREF", p_reqB319.clientRef);//在线融资申请使用的交易流水号
            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString());
            if (tmpRetBkStr[0].length() == 0) {
                String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                if (tmpBkReader != null) {
                    //响应结果
                    String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                    String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/MESSAGE");
                    if ("0".equals(trspcod)) {
                        String retCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/REBUILDCONTRACTTRNRS/STATUS/CODE");
                        String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/REBUILDCONTRACTTRNRS/STATUS/MESSAGE");
                        if ("0".equals(retCode)) {
                            //处理结果
                            String resultCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/REBUILDCONTRACTTRNRS/RSBODY/RESULTCODE");
                            if ("01".equals(resultCode)) {
                                retAts.respCode = "0";
                                retAts.respInfo = "重新生成成功，请调用融资申请处理结果查询下载：" + statusMessage;
                                retAts.payInfoCode = "rebuildFileSucs";
                                retAts.transState = retAts.payInfoCode;
                                retAts.reqSeqID = p_reqB319.clientRef;
                            } else {
                                retAts.respCode = "0";
                                retAts.respInfo = "重新生成失败，请重新请求，如多次失败请联系银行：" + statusMessage;
                                retAts.payInfoCode = "rebuildFileFail";
                                retAts.transState = retAts.payInfoCode;
                                retAts.reqSeqID = p_reqB319.clientRef;
                            }
                        } else {
                            retAts.respCode = "0";
                            retAts.respInfo = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/REBUILDCONTRACTTRNRS/STATUS/MESSAGE");
                            retAts.payInfoCode = "rebuildFileFail";
                            retAts.transState = retAts.payInfoCode;
                            retAts.reqSeqID = p_reqB319.clientRef;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = trspmsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpRetBkStr[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn("重新生成合同文件异常：" + e);
        } finally {
            conn.close();
        }
        //增加批次状态
        if ("0".equals(retAts.respCode)) {
            retAts.batchState = "2";
        }
        retAts.writeAfter();
        return retAts;
    }

    /**
     * 融资合同申请确认
     * @param p_reqB320
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB320ConfirmApplicationContract BP904_ConfirmApplicationContract(ReqB320ConfirmApplicationContract p_reqB320) throws Exception {
        RetAtsB320ConfirmApplicationContract retAts = new RetAtsB320ConfirmApplicationContract(p_reqB320.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        //根据在线融资申请使用的交易流水号，查询文件路径（包括名字）
        //判断文件是否存在，存在进行MD5加密做参数发送报文
        try {
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{p_reqB320.clientRef, p_reqB320.reqHeader.bankCode});
            if (map.size() <= 0) {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到记录，请先下载合同文件";
                retAts.writeAfter();
                return retAts;
            }
            String localFilePath = map.get("RESERVE1").toString();
            if (FileHelper.existFile(localFilePath)) {
                WriteBankLogLn("获取到本地合同文件：" + localFilePath);
                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonBillPoolHeaderEn(xmlWriter);
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
                xmlWriter.writeStartElement("CONFIRMDRAWFINTRNRQ");
                xmlWriter.writeElementString("TRNUID", p_reqB320.reqHeader.transSeqID);//客户端交易的唯一流水号
                xmlWriter.writeStartElement("RQBODY");
                xmlWriter.writeElementString("SIGNATURE", "01");
                xmlWriter.writeElementString("MDKEY", DigestHelper.cryptoMD5ByFilePath(localFilePath));
                xmlWriter.writeElementString("CLIENTREF", p_reqB320.clientRef);//在线融资申请使用的交易流水号
                xmlWriter.writeEndDocument();
                String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString());
                if (tmpRetBkStr[0].length() == 0) {
                    String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                    if (tmpBkReader != null) {
                        //响应结果
                        String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                        String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/SEVERITY");
                        if ("0".equals(trspcod)) {
                            //处理结果
                            String retCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/CONFIRMDRAWFINTRNRS/STATUS/CODE");
                            String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/CONFIRMDRAWFINTRNRS/STATUS/MESSAGE");
                            if ("0".equals(retCode)) {
                                //处理结果
                                String result = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/CONFIRMDRAWFINTRNRS/RSBODY/RESULT");
                                if ("CG".equals(result)) {
                                    retAts.respCode = "0";
                                    retAts.respInfo = statusMessage;
                                    retAts.payInfoCode = retCode + "+" + result;//0+CG 合同确认成功
                                    retAts.transState = retAts.payInfoCode;
                                    retAts.reqSeqID = p_reqB320.clientRef;
                                    retAts.applySeqID = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/CONFIRMDRAWFINTRNRS/RSBODY/APPLYCODE");
                                } else {
                                    retAts.respCode = "0";
                                    retAts.respInfo = "合同确认失败，请重新确认：" + statusMessage;
                                    retAts.payInfoCode = retCode + "+" + "SB";//合同确认失败
                                    retAts.transState = retAts.payInfoCode;
                                    retAts.reqSeqID = p_reqB320.clientRef;
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = statusMessage;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = trspmsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpRetBkStr[1];
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "融资申请合同本地映射文件不存在，请点击重新生成合同文件！";
                WriteBankLogLn("融资申请合同本地映射文件不存在！本地映射文件路径：" + localFilePath);
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn("融资申请合同确认异常：" + e);
        } finally {
            conn.close();
        }
        //增加批次状态
        if ("0".equals(retAts.respCode)) {
            retAts.batchState = "2";
        }
        retAts.writeAfter();
        return retAts;
    }

    @Override
    public RetAtsB321QryFinancingApply BP905_QryFinancingApply(ReqB321QryFinancingApply p_reqB321) throws Exception {
        RetAtsB321QryFinancingApply retAts = new RetAtsB321QryFinancingApply(p_reqB321.reqHeader);
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonBillPoolHeaderEn(xmlWriter);
        xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
        xmlWriter.writeStartElement("QUERYDRAWFINDTLTRNRQ");
        xmlWriter.writeElementString("TRNUID", p_reqB321.reqHeader.transSeqID);//客户端交易的唯一流水号
        xmlWriter.writeStartElement("RQBODY");
        xmlWriter.writeElementString("OPERATEFLAG", "1");
        xmlWriter.writeElementString("APPLYCODE ", p_reqB321.applySeqId);//申请代码
        xmlWriter.writeElementString("SRVRID", p_reqB321.billSeqId);//商票网银客户号
        xmlWriter.writeEndDocument();
        String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString());
        if (tmpRetBkStr[0].length() == 0) {
            String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
            StringBuilder tmpSbMsg = new StringBuilder();
            XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
            if (tmpBkReader != null) {
                //响应结果
                String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/SEVERITY");
                if ("0".equals(trspcod)) {
                    //处理结果
                    String retCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINDTLTRNRS/STATUS/CODE");
                    String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINDTLTRNRS/STATUS/MESSAGE");
                    if ("0".equals(retCode)) {
                        retAts.respCode = "0";
                        retAts.respInfo = statusMessage;
                        retAts.reqSeqID = p_reqB321.clientRef;
                        retAts.transState = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINDTLTRNRS/RSBODY/APPLYSTATUS");//申请状态
                        retAts.payInfoCode = retAts.transState;
                        if ("YT".equals(retAts.transState) || "YF".equals(retAts.transState)) {
                            retAts.batchState = "2";
                        } else if ("SL".equals(retAts.transState)) {
                            retAts.batchState = "4";
                        } else if ("CZ".equals(retAts.transState)) {
                            retAts.batchState = "6";
                        } else if ("JQ".equals(retAts.transState)) {
                            retAts.batchState = "7";
                        } else if ("TH".equals(retAts.transState)) {
                            retAts.batchState = "8";
                        }
                        retAts.writeBeforeDetail();
                        while (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/QUERYDRAWFINDTLTRNRS/RSBODY/CONTENT")) {
                            RetAtsB321QryFinancingApplyDetail detail = new RetAtsB321QryFinancingApplyDetail();
                            detail.billNo = tmpBkReader.readedXElement.getSingleTextNotNull("BILLCODE");//电子票据号码
                            String billType = tmpBkReader.readedXElement.getSingleTextNotNull("BILLTYPE");
                            detail.billType = "AC01".equals(billType) ? "1" : ("AC02".equals(billType) ? "2" : "");//票据类型 1-银承 2-商承
                            detail.issDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("DRAWDATE"));//出票日(yyyy-MM-dd)
                            detail.dueDate = DateHelper.convertD8toD10(tmpBkReader.readedXElement.getSingleTextNotNull("DUEDATE"));//到期日(yyyy-MM-dd)
                            detail.billAmt = tmpBkReader.readedXElement.getSingleTextNotNull("BILLAMT");//电子票据金额
                            detail.drawName = tmpBkReader.readedXElement.getSingleTextNotNull("DRAWER/NAME");//出票人
                            detail.drawAct = tmpBkReader.readedXElement.getSingleTextNotNull("DRAWER/ACCTID");//出票人账号
                            detail.drawBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("DRAWER/BANKNUM");//出票人开户行行号
                            detail.accpName = tmpBkReader.readedXElement.getSingleTextNotNull("ACACCT/NAME");//承兑人名称
                            detail.accpAct = tmpBkReader.readedXElement.getSingleTextNotNull("ACACCT/ACCTID");//承兑人账号
                            detail.accpBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("ACACCT/BANKNUM");//承兑人开户行行号
                            detail.payeeName = tmpBkReader.readedXElement.getSingleTextNotNull("PAYEEACCT/NAME");//收款人
                            detail.payeeAct = tmpBkReader.readedXElement.getSingleTextNotNull("PAYEEACCT/ACCTID");//收款人账号
                            detail.payeeBnkCode = tmpBkReader.readedXElement.getSingleTextNotNull("PAYEEACCT/BANKNUM");//收款人开户行行号
                            String transFlag = tmpBkReader.readedXElement.getSingleTextNotNull("NEGTBL");
                            detail.transFlag = "EM00".equals(transFlag) ? "1" : ("EM01".equals(transFlag) ? "0" : "");//转让标识
                            detail.billStatus = tmpBkReader.readedXElement.getSingleTextNotNull("BILLSTATUS");//票据状态
                            retAts.writeRetDetail(detail);
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = statusMessage;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = trspmsg;
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpSbMsg.toString();
            }
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = tmpRetBkStr[1];
        }
        if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqB321.clientRef;
        }
        if ("-1".equals(retAts.respCode)) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    /**
     * 票据池可操作票据查询
     * @param query
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB301OperBillQry BP001_OperBill_Req(ReqB301OperBillQry query) throws Exception {
        /**
         * 注意！！兴业银行，该接口与电票B001接口兴业银行可操作票据查询接口使用的是同一个银行提供的接口
         * 修改时注意两个接口的实现类都要进行修改
         */
        RetAtsB301OperBillQry retAts = new RetAtsB301OperBillQry(query.reqHeader);
        retAts.writeStart();
        retAts.RespCode = "0";
        try {
//                    <BUSINESSTYPE/>	业务编码
//                1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
            String businessType;
            int busiType = Integer.valueOf(query.BusiType);
            if ("1".equals(query.QueryType)) {
                switch (busiType) {
                    case 1:
                        businessType = "01";
                        break;//出票
                    case 2:
                        businessType = "03";
                        break;//承兑
                    case 3:
                        businessType = "05";
                        break;//收票
                    case 4:
                        businessType = "07";
                        break;//背书
                    case 5:
                        businessType = "15";
                        break;//质押
                    case 6:
                        businessType = "16";
                        break;//解质押
                    case 10:
                        businessType = "09";
                        break;//贴现
                    case 12:
                        businessType = "17";
                        break;//提示付款
                    case 13:
                        if ("1".equals(query.RecourseType)) {
                            businessType = "19";//拒付
                        } else {
                            businessType = "20";//非拒付
                        }
                        break;//追索
                    case 14:
                        businessType = "21";
                        break;//清偿
                    default:
                        throw new Exception("未知的业务类型：" + query.BusiType);
                }
            } else if ("2".equals(query.QueryType)) {
                switch (busiType) {
                    case 2:
                        businessType = "03";
                        break;//承兑
                    case 3:
                        businessType = "05";
                        break;//收票
                    case 4:
                        businessType = "07";
                        break;//背书
                    case 5:
                        businessType = "15";
                        break;//质押
                    case 6:
                        businessType = "16";
                        break;//押解
                    case 11:
                        businessType = "10";
                        break;//贴现
                    case 14:
                        businessType = "21";
                        break;//同意清偿
                    default:
                        throw new Exception("未知的业务类型:" + query.BusiType);
                }
            } else if ("3".equals(query.QueryType)) {
                switch (busiType) {
                    case 1:
                        businessType = "06";
                        break;//撤票
                    case 2:
                        businessType = "22";
                        break;//承兑撤回
                    case 3:
                        businessType = "23";
                        break;//收票撤回
                    case 4:
                        businessType = "24";
                        break;//背书撤回
                    case 5:
                        businessType = "33";
                        break;//质押撤回
                    case 6:
                        businessType = "34";
                        break;//解质押撤回
                    case 10:
                        businessType = "25";
                        break;//贴现撤回
                    case 12:
                        businessType = "35";
                        break;//提示付款撤回
                    case 13:
                        businessType = "38";
                        break;//追索通知撤回
                    case 14:
                        businessType = "37";
                        break;//同意清偿撤回
                    default:
                        throw new Exception("未知的业务类型:" + query.BusiType);
                }
            } else {
                throw new Exception("未知的查询类型：" + query.QueryType);
            }

            if ("2".equals(query.QueryType)) {
                queryOperBill_ebsignquerytrnrq(retAts, query, businessType);//查询可签收的票据
            } else {
                queryOperBill_eboprnquerytrnrq(retAts, query, businessType);//可操作票据查询
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts = new RetAtsB301OperBillQry(query.reqHeader);
            retAts.writeStart();
            retAts.RespCode = "-1";
            retAts.RespInfo = ex.getMessage();
        }
        retAts.writeCodeInfo();
        retAts.writeEnd();
        return retAts;
    }

    public void queryOperBill_eboprnquerytrnrq(RetAtsB301OperBillQry retAts, ReqB301OperBillQry req_B301, String buisType) throws Exception {
        StringBuilder errorMsg = new StringBuilder();//错误信息
        int countNum = 0;//查询票据总数
        List<String> billTypeList = new ArrayList<String>();
        if (StringHelper.isNullOrEmpty(req_B301.BillType) || "0".equals(req_B301.BillType)) {
            billTypeList.add("AC01");
            billTypeList.add("AC02");
        } else {
            billTypeList.add("1".equals(req_B301.BillType) ? "AC01" : "AC02");
        }
        for (int i = 0; i < billTypeList.size(); i++) {
            WriteBankLogLn("查询票据类型：" + billTypeList.get(i) + "的票据...");
            boolean more = true;
            int page = 1;
            while (more) {
                more = false;
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeaderEn(xmlWriter, "encoding=\"gb2312\"");
//            < SECURITIES_MSGSRQV1>	请求服务指令消息集	必输
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
//                    <EBOPRNQUERYTRNRQ>	服务标识	必输
                xmlWriter.writeStartElement("EBOPRNQUERYTRNRQ");
//            <TRNUID/>	客户端交易的唯一流水号
                String trnuId = getQryTransID();
                xmlWriter.writeElementString("TRNUID", trnuId);
//            建议值为YYYYMMDD+序号，最长30位	必输
//            <RQBODY PAGE=“1”>	消息报文体,PAGE页码数	必输
                xmlWriter.writeElementAttribute("RQBODY", "PAGE", page + "");
//            <BUSINESSTYPE/>	业务编码
                xmlWriter.writeElementString("BUSINESSTYPE", buisType);
//            参见附录《电子票据系统编码对照表》	必输
//                    <BILLCODE/>	票据号码	非必输
                if (StringHelper.hasAnyChar(req_B301.BilNo)) {
                    xmlWriter.writeElementString("BILLCODE", req_B301.BilNo);
                }
//            <ACCTID/>	查询账户代号	必输
                xmlWriter.writeElementString("ACCTID", req_B301.AccountNum);
                if (StringHelper.hasAnyChar(req_B301.BillDateLowLimit) || StringHelper.hasAnyChar(req_B301.BillDateTopLimit)) {
                    //            <DUEDATE>	票据到期日日期范围	非必输
                    xmlWriter.writeStartElement("DUEDATE");
                    //                    <DTSTART/>
                    xmlWriter.writeElementString("DTSTART", req_B301.BillDateLowLimit);
                    //            <DTEND/>
                    xmlWriter.writeElementString("DTEND", req_B301.BillDateTopLimit);
                    //            </DUEDATE>
                    xmlWriter.writeEndElement();
                }
                if (StringHelper.hasAnyChar(req_B301.BillMoneyLowLimit) || StringHelper.hasAnyChar(req_B301.BillMoneyTopLimit)) {
                    //            <BILLAMT>	票据金额范围	非必输
                    xmlWriter.writeStartElement("BILLAMT");
                    //                    <MINAMT/>
                    xmlWriter.writeElementString("MINAMT", req_B301.BillMoneyLowLimit);
                    //            <MAXAMT/>
                    xmlWriter.writeElementString("MAXAMT", req_B301.BillMoneyTopLimit);
                    //            </BILLAMT>
                    xmlWriter.writeEndElement();
                }
//            </>	票据种类BILLTYPE	非必输
                xmlWriter.writeElementString("BILLTYPE", billTypeList.get(i));


//                    </RQBODY>
//            </EBOPRNQUERYTRNRQ>
//            </ SECURITIES_MSGSRQV1>
                xmlWriter.writeEndDocument();
                String xmlSend = writeContentLength(xmlWriter);
                String[] result = sendToBank(xmlSend);
                if (result[0].length() == 0) {
                    String returnXml = result[1].substring(result[1].indexOf("<FOX>"), result[1].length());
                    StringBuilder tmpSbmsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbmsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBOPRNQUERYTRNRS/STATUS/CODE");
                        String returnMsg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBOPRNQUERYTRNRS/STATUS/MESSAGE");
                        if ("0".equals(returnCode)) {
                            if (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBOPRNQUERYTRNRS/RSBODY")) {
                                String moreStr = tmpBkReader.readedXElement.getAttrValue("MORE");
                                if (StringHelper.hasAnyChar(moreStr) && moreStr.equals("Y")) {
                                    more = true;
                                    page++;
                                } else {
                                    more = false;
                                }
                            } else {
                                return;
                            }
                            ArrayList<XElement> list = tmpBkReader.readedXElement.getChildList("CONTENT");
                            if (list != null) {
                                for (XElement xElement : list) {
                                    RetAtsB301OperBillQryDetail detail = new RetAtsB301OperBillQryDetail();
                                    //电子票据号码
                                    detail.BillNum = xElement.getSingleText("BILLCODE");
                                    //票据类型 1-银承 2-商承
                                    String billType2 = xElement.getSingleText("BILLTYPE");
                                    if ("AC01".equals(billType2)) {
                                        detail.BillType = "1";
                                    } else if ("AC02".equals(billType2)) {
                                        detail.BillType = "2";
                                    }
                                    //出票日
                                    detail.DrawDate = xElement.getSingleText("DRAWDATE");
                                    //到期日
                                    detail.DueDate = xElement.getSingleText("DUEDATE");
                                    //电子票据金额
                                    detail.BillMoney = xElement.getSingleText("BILLAMT");
                                    String transFlag = xElement.getSingleText("NEGTBL");
                                    //背书转让标识 1-可再转让 0-不得转让
                                    if ("EM00".equals(transFlag)) {
                                        detail.TransFlag = "1";
                                    } else if ("EM01".equals(transFlag)) {
                                        detail.TransFlag = "0";
                                    }
                                    //出票人
                                    detail.BillDrawer = xElement.getSingleText("DRAWERACCT/NAME");
                                    //出票人账号
                                    detail.DrawerAccount = xElement.getSingleText("DRAWERACCT/ACCTID");
                                    //出票人开户行行号
                                    detail.DrawerCNAPSCode = xElement.getSingleText("DRAWERACCT/BANKNUM");
                                    //承兑人名称
                                    detail.Acceptor = xElement.getSingleText("ACPTRACCT/NAME");
                                    //承兑人账号
                                    detail.AcceptorAccountNum = xElement.getSingleText("ACPTRACCT/ACCTID");
                                    //承兑人开户行行号
                                    detail.AcceptorCNAPSCode = xElement.getSingleText("ACPTRACCT/BANKNUM");
                                    //收款人
                                    detail.Payee = xElement.getSingleText("PAYEEACCT/NAME");
                                    //收款人账号
                                    detail.PayeeAccountNum = xElement.getSingleText("PAYEEACCT/ACCTID");
                                    //收款人开户行行号
                                    detail.PayeeCNAPSCode = xElement.getSingleText("PAYEEACCT/BANKNUM");
                                    //交易明细流水
                                    String seq = xElement.getSingleTextNotNull("SEQ");
                                    String bizflag = xElement.getSingleTextNotNull("BIZFLAG");
                                    detail.BusiNo = seq + "@" + bizflag;
                                    //操作标志
                                    detail.BusiType = req_B301.BusiType;
                                    detail.QueryType = req_B301.QueryType;

                                    detail.ApplyDate = xElement.getSingleText("APPDATE");
                                    //票据状态
                                    detail.BillState = xElement.getSingleText("BILLSTATUS");
                                    retAts.writeDetail(detail);
                                    countNum++;
                                }
                            } else {
                                errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(returnMsg).append(";\r\r");
//                                throw new Exception(returnMsg);
                            }
                        } else {
                            errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(returnMsg).append(";\r\r");
//                            throw new Exception(returnMsg);
                        }
//                    <EBOPRNQUERYTRNRS>
//                    <TRNUID>20120504cx10</TRNUID>
//                    <STATUS>
//                    <CODE>0</CODE>
//                    <SEVERITY>INFO</SEVERITY>
//                    <MESSAGE>处理成功！</MESSAGE>
//                    </STATUS>
//                    <RSBODY MORE="N">

                    } else {
                        errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(tmpSbmsg.toString()).append(";\r\r");
//                        throw new Exception(tmpSbmsg.toString());
                    }
                } else {
                    errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(result[1]).append(";\r\r");
//                    throw new Exception(result[1]);
                }
            }
        }
        if (countNum == 0 && errorMsg.length() > 0) {
            throw new Exception(errorMsg.toString());
        } else if (countNum > 0 && errorMsg.length() > 0) {
            retAts.RespInfo = errorMsg.toString();
        } else {
            retAts.RespInfo = "查询成功！";
        }
    }

    public void queryOperBill_ebsignquerytrnrq(RetAtsB301OperBillQry retAts, ReqB301OperBillQry req_B301, String buisType) throws Exception {
        StringBuilder errorMsg = new StringBuilder();//错误信息
        int countNum = 0;//查询票据总数
        List<String> billTypeList = new ArrayList<String>();
        if (StringHelper.isNullOrEmpty(req_B301.BillType) || "0".equals(req_B301.BillType)) {
            billTypeList.add("AC01");
            billTypeList.add("AC02");
        } else {
            billTypeList.add("1".equals(req_B301.BillType) ? "AC01" : "AC02");
        }
        for (int i = 0; i < billTypeList.size(); i++) {
            WriteBankLogLn("查询票据类型：" + billTypeList.get(i) + "的票据...");
            boolean more = true;
            int page = 1;
            while (more) {
                more = false;
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeaderEn(xmlWriter, "encoding=\"gb2312\"");
//            < SECURITIES_MSGSRQV1>	请求服务指令消息集	必输
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
//                    <EBSIGNQUERYTRNRQ>		必输
                xmlWriter.writeStartElement("EBSIGNQUERYTRNRQ");
//                    <TRNUID/>	客户端交易的唯一流水号
                String trnuId = getQryTransID();
                xmlWriter.writeElementString("TRNUID", trnuId);
//            建议值为YYYYMMDD+序号，最长30位	必输
//            <RQBODY PAGE=“1”>	PAGE查询页码，必输	必输
                xmlWriter.writeElementAttribute("RQBODY", "PAGE", page + "");
//            <BUSINESSTYPE/>	业务种类，见附录3	必输
                xmlWriter.writeElementString("BUSINESSTYPE", buisType);
//            <BILLCODE/>	票据号码,30位	非必输
                if (!StringHelper.isNullOrEmpty(req_B301.BilNo)) {
                    xmlWriter.writeElementString("BILLCODE", req_B301.BilNo);
                }
//            <ACCTID/>	操作员账户代号（将进行签收的操作账号）
                xmlWriter.writeElementString("ACCTID", req_B301.AccountNum);
//            最大32位	必输
//            <APPDTSTART>	对方行业务申请日期范围
//                    <DTSTART/>	起始日期 YYYY-MM-DD
//                    <DTEND/>	结束日期 YYYY-MM-DD
//                    </APPDTSTART>
                xmlWriter.writeStartElement("APPDTSTART");
                Date now = new Date();
                String endDate = Format.Date10Format.format(now);
                int month = getBankConfig().getValueAsInt("monthInterval");
                if (month == -1) {
                    month = -3;
                } else {
                    month = 0 - month;
                }
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(now);
                calendar.add(Calendar.MONTH, month);
                xmlWriter.writeElementString("DTSTART", Format.Date10Format.format(calendar.getTime()));
                xmlWriter.writeElementString("DTEND", endDate);
                xmlWriter.writeEndElement();

//            <BILLAMT>	票据金额范围	非必输
                if (StringHelper.hasAnyChar(req_B301.BillMoneyTopLimit) && StringHelper.hasAnyChar(req_B301.BillMoneyLowLimit)) {
                    xmlWriter.writeStartElement("BILLAMT");
//                    <MINAMT/>	最小金额,17位(15整数位,2小数位)
                    xmlWriter.writeElementString("MINAMT", req_B301.BillMoneyLowLimit);
//                    <MAXAMT/>	最大金额,17位(15整数位,2小数位)
                    xmlWriter.writeElementString("MAXAMT", req_B301.BillMoneyTopLimit);
//                    </BILLAMT>
                    xmlWriter.writeEndElement();
                }
//            <BILLTYPE/>	票据类型(AC01:银票,AC02:商票)	非必输
                xmlWriter.writeElementString("BILLTYPE", billTypeList.get(i));

//                    </RQBODY>
//            </EBSIGNQUERYTRNRQ>
//            </SECURITIES_MSGSRSV1>
                xmlWriter.writeEndDocument();
                String xmlSend = writeContentLength(xmlWriter);
                String[] result = sendToBank(xmlSend);
                if (result[0].length() == 0) {
                    String returnXml = result[1].substring(result[1].indexOf("<FOX>"), result[1].length());
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBSIGNQUERYTRNRS/STATUS/CODE");
                        String returnMsg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBSIGNQUERYTRNRS/STATUS/MESSAGE");
                        if ("0".equals(returnCode)) {
                            if (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBSIGNQUERYTRNRS/RSBODY")) {
                                String moreStr = tmpBkReader.readedXElement.getAttrValue("MORE");
                                if (StringHelper.hasAnyChar(moreStr) && moreStr.equals("Y")) {
                                    more = true;
                                    page++;
                                } else {
                                    more = false;
                                }
                            } else {
                                return;
                            }
                            ArrayList<XElement> list = tmpBkReader.readedXElement.getChildList("CONTENT");
                            if (list != null) {
                                for (XElement xElement : list) {
                                    RetAtsB301OperBillQryDetail detail = new RetAtsB301OperBillQryDetail();
//
//                                        <BUSINESSTYPE/>	业务类型
//                                        <BILLCODE/>	30位票据号码
                                    detail.BillNum = xElement.getSingleText("BILLCODE");
//                                        <BILLTYPE/>	票据类型,4位(AC01:银票,AC02:商票)
                                    String billType = xElement.getSingleTextNotNull("BILLTYPE");
                                    if ("AC01".equals(billType)) {
                                        detail.BillType = "1";
                                    } else if ("AC02".equals(billType)) {
                                        detail.BillType = "2";
                                    }
//                                <BILLAMT/>	票据金额,17位(15整数位,2小数位)
                                    detail.BillMoney = xElement.getSingleTextNotNull("BILLAMT");
//                                        <DRAWDATE/>	出票日期
                                    detail.DrawDate = xElement.getSingleText("DRAWDATE");
//                                        <DUEDATE/>	票据到期日
                                    detail.DueDate = xElement.getSingleText("DUEDATE");
//                                        <NEGTBL/>	可否转让标识,
//                                        4位(EM00:可再转让,EM01:不可再转让)
                                    String transFlag = xElement.getSingleText("NEGTBL");
                                    if ("EM00".equals(transFlag)) {
                                        detail.TransFlag = "1";
                                    } else if ("EM01".equals(transFlag)) {
                                        detail.TransFlag = "0";
                                    }
//                                <BILLSTATUS/>	票据状态,6位见附录：票据状态表
                                    detail.BillState = xElement.getSingleText("BILLSTATUS");
//                                        <DRAWERACCT>	出票人账户信息
//                                <ACCTID/>	账户代号,最大32位
                                    detail.DrawerAccount = xElement.getSingleText("DRAWERACCT/ACCTID");
//                                        <NAME/>	账户名称,最大60位
                                    detail.BillDrawer = xElement.getSingleText("DRAWERACCT/NAME");
//                                        <BANKNUM/>	开户行号,最大12位
                                    detail.DrawerCNAPSCode = xElement.getSingleText("DRAWERACCT/BANKNUM");
//                                        <ORGID/>	组织机构代码,最小1位,最大10位
                                    detail.DrawCode = xElement.getSingleText("DRAWERACCT/ORGID");
//                                        </DRAWERACCT>
//                                <ACPTRACCT>	承兑人账户信息
//                                        <ACCTID/>	账户代号,最大32位
                                    detail.AcceptorAccountNum = xElement.getSingleText("ACPTRACCT/ACCTID");
//                                        <NAME/>	账户名称,最大60位
                                    detail.Acceptor = xElement.getSingleText("ACPTRACCT/NAME");
//                                        <BANKNUM/>	开户行号,最大12位
                                    detail.AcceptorCNAPSCode = xElement.getSingleText("ACPTRACCT/BANKNUM");
//                                        </ACPTRACCT>
//                                <PAYEEACCT>	收款人账户信息
//                                        <ACCTID/>	账户代号,最大32位
                                    detail.PayeeAccountNum = xElement.getSingleText("PAYEEACCT/ACCTID");
//                                        <NAME/>	账户名称,最大60位
                                    detail.Payee = xElement.getSingleText("PAYEEACCT/NAME");
//                                        <BANKNUM/>	开户行号,最大12位
                                    detail.PayeeCNAPSCode = xElement.getSingleText("PAYEEACCT/BANKNUM");
//                                        </PAYEEACCT>
//                                <BIZFLAG/>	商票系统业务标识号
                                    detail.BusiNo = xElement.getSingleText("BIZFLAG");
//                                        <ENTRSPAY/>	到期无条件支付委托
                                    String mustPay = xElement.getSingleText("");
                                    if ("CC00".equals(mustPay)) {
                                        detail.MustPay = "1";
                                    } else {
                                        detail.MustPay = "0";
                                    }
//                                        <APPDATE/>	业务申请日期
                                    detail.ApplyDate = xElement.getSingleText("APPDATE");
//                                        <PROPSRINFO>	业务申请人信息
//                                        <ACCTID/>	账户代号,最大32位
                                    detail.ApplyAct = xElement.getSingleText("PROPSRINFO/ACCTID");
//                                        <NAME/>	账户名称,最大60位
                                    detail.ApplyName = xElement.getSingleText("PROPSRINFO/NAME");
//                                        <BANKNUM/>	开户行号,最大12位
                                    detail.ApplyBnkCode = xElement.getSingleText("PROPSRINFO/BANKNUM");
//                                        <ORGID/>	组织机构代码,最小1位,最大10位
                                    detail.ApplyCode = xElement.getSingleText("PROPSRINFO/ORGID");
//                                        </PROPSRINFO>
//                                <RCVRRINFO>	业务接收人信息
//                                        <ACCTID/>	账户代号,最大32位
                                    detail.ReceAct = xElement.getSingleText("RCVRRINFO/ACCTID");
//                                        <NAME/>	账户名称,最大60位
                                    detail.ReceName = xElement.getSingleText("RCVRRINFO/NAME");
//                                        <BANKNUM/>	开户行号,最大12位
                                    detail.ReceBnkCode = xElement.getSingleText("RCVRRINFO/receBnkCode");
//                                        <ORGID/>	组织机构代码,最小1位,最大10位
                                    detail.ReceCode = xElement.getSingleText("RCVRRINFO/ORGID");
//                                        </RCVRRINFO>
//                                <DISCNTTYPE/>	贴现类型,4位(RM00:买断式,RM01回购式)
                                    String discType = xElement.getSingleText("DISCNTTYPE");
                                    if ("RM00".equals(discType)) {
                                        detail.DiscType = "1";
                                    } else if ("RM01".equals(discType)) {
                                        detail.DiscType = "2";
                                    }
//                                <DISCNTINTRSTRATE/>	贴现利率,7位百分数不含百分号
                                    detail.DiscRate = xElement.getSingleText("DISCNTINTRSTRATE");
//                                        (2位整数,5位小数)
//                                        <REDMDATE>	回购日期范围
//                                        <DTSTART/>	起始日期,YYYY-MM-DD
                                    detail.RepOpenDate = xElement.getSingleText("REDMDATE/DTSTART");
//                                        <DTEND/>	结束日期,YYYY-MM-DD
                                    detail.RepDueDate = xElement.getSingleText("REDMDATE/DTEND");
//                                        </REDMDATE>
//                                <REDMINTRSTRATE/>	赎回利率,7位百分数不含百分号(2位整数,5位小数)
                                    detail.RepRate = xElement.getSingleText("REDMINTRSTRATE");
//                                        <LQMODE/>	清算模式,4位
//                                        (SM00:线上清算,SM01:线下清算)
                                    String payType = xElement.getSingleText("");
                                    if ("SM00".equals(payType)) {
                                        detail.PayType = "1";
                                    } else if ("SM01".equals(payType)) {
                                        detail.PayType = "2";
                                    }
//                                        <RECRSAMT/>	追索金额,17位(15整数位,2小数位)
                                    detail.RecourseAmt = xElement.getSingleText("RECRSAMT");
//                                        <MEMO/>	备注,最大256位
                                    detail.Memo = xElement.getSingleTextNotNull("MEMO");
//                                        <OVERDUEREASON/>	逾期原因	非必回
                                    detail.OverDueRea = xElement.getSingleTextNotNull("OVERDUEREASON");
//                                        <TRANSCONTRACENO/>	交易合同号	非必回
                                    detail.ContractNo = xElement.getSingleTextNotNull("TRANSCONTRACENO");
//                                </CONTENT>
//                                </RSBODY>
//                                </EBSIGNQUERYTRNRS>
//                                </SECURITIES_MSGSRSV1>
                                    retAts.writeDetail(detail);
                                    countNum++;
                                }
                            } else {
                                errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(returnMsg).append(";\r\r");
//                                throw new Exception(returnMsg);
                            }
                        } else {
                            errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(returnMsg).append(";\r\r");
//                            throw new Exception(returnMsg);
                        }
//                    <EBOPRNQUERYTRNRS>
//                    <TRNUID>20120504cx10</TRNUID>
//                    <STATUS>
//                    <CODE>0</CODE>
//                    <SEVERITY>INFO</SEVERITY>
//                    <MESSAGE>处理成功！</MESSAGE>
//                    </STATUS>
//                    <RSBODY MORE="N">

                    } else {
                        errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(tmpSbMsg.toString()).append(";\r\r");
//                        throw new Exception(tmpSbMsg.toString());
                    }
                } else {
                    errorMsg.append("查询票据类型：").append(billTypeList.get(i)).append("的票据:").append(result[1]).append(";\r\r");
//                    throw new Exception(result[1]);
                }
            }
        }
        if (countNum == 0 && errorMsg.length() > 0) {
            throw new Exception(errorMsg.toString());
        } else if (countNum > 0 && errorMsg.length() > 0) {
            retAts.RespInfo = errorMsg.toString();
        } else {
            retAts.RespInfo = "查询成功！";
        }
    }

    /**
     * 入池质押申请
     * @param req_b302
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB302InPoolPledge BP101_InPoolPledge_Req(ReqB302InPoolPledge req_b302) throws Exception {
        RetAtsB302InPoolPledge retAts = new RetAtsB302InPoolPledge(req_b302.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        StringBuilder errorMsg = new StringBuilder();
        try {
            while (req_b302.readRecord()) {
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonBillPoolHeaderEn(xmlWriter);
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
                xmlWriter.writeStartElement("EBIMPAWNTRNRQ");
                String Trnuid = req_b302.detail.ReqSeqID + getINDX();
                xmlWriter.writeElementString("TRNUID", Trnuid);//客户端交易的唯一流水号 建议值为YYYYMMDD + 序号，最长30位
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, req_b302.reqHeader.bankCode, req_b302.detail.ReqSeqID, Trnuid, ""});
                xmlWriter.writeStartElement("RQBODY");
                xmlWriter.writeElementString("TOTALCOUNT", "1");//票据总笔数
                xmlWriter.writeElementString("TOTALAMT", req_b302.detail.BillMoney);//票据总金额
                if (StringHelper.isNullOrEmpty(req_b302.Appdate)) {
                    xmlWriter.writeElementString("APPDATE", Format.Date10Format.format(new Date()));//质押申请日期,YYYY-MM-DD
                } else {
                    xmlWriter.writeElementString("APPDATE", req_b302.Appdate);//质押申请日期,YYYY-MM-DD
                }
                xmlWriter.writeStartElement("ACCTFROM");//出质人账户信息
                xmlWriter.writeElementString("ACCTID", req_b302.detail.AccountNum);//出质人账户代号
                xmlWriter.writeEndElement();//ACCTFROM
                if (StringHelper.isNullOrEmpty(req_b302.detail.BillType)) {
                    errorMsg.append(req_b302.detail.BillNum).append(":入池质押票据类型（BillType）必填！").append("\r\n");
                    continue;
                }
                xmlWriter.writeElementString("BILLTYPE", "1".equals(req_b302.detail.BillType) ? "AC01" : "AC02");//票据类型,4位(AC01:银票,AC02:商票)
                xmlWriter.writeElementString("ISCIB", req_b302.detail.Iscib);//质权人是否兴业账户,1位(Y:是,N:否)
                xmlWriter.writeStartElement("ACCTTO");//质权人账户信息
                xmlWriter.writeElementString("ACCTID", req_b302.detail.PawneeAccount);//质权人账户代号
                xmlWriter.writeElementString("NAME", req_b302.detail.PawneeName);//质权人账户名称
                xmlWriter.writeElementString("BANKNUM", req_b302.detail.PawneeCNAPSCode);//质权人账户开户行行号
                xmlWriter.writeEndElement();//ACCTTO
                xmlWriter.writeElementString("MEMO", req_b302.detail.Remark);//出质人备注
                xmlWriter.writeStartElement("CONTENT");
                xmlWriter.writeElementString("INDX", "0001");//小序号,4位
                xmlWriter.writeElementString("BILLCODE", req_b302.detail.BillNum);//票据号码
                xmlWriter.writeElementString("BILLAMT", req_b302.detail.BillMoney);//票据金额
                xmlWriter.writeEndElement();//CONTENT
                xmlWriter.writeEndDocument();

                String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString(), req_b302.reqHeader.transType, req_b302.reqHeader.transType);

                if (tmpRetBkStr[0].length() == 0) {
                    String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                    if (tmpBkReader != null) {
                        retAts.RespCode = "0";
                        RetAtsB302InPoolPledgeDetail retAtsDetail = new RetAtsB302InPoolPledgeDetail();
                        //响应结果
                        String trspcod = tmpBkReader.getFirstTextNotNull("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                        String trspmsg = tmpBkReader.getFirstTextNotNull("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/MESSAGE");
                        if (trspcod != null && "0".equals(trspcod)) {
                            //交易处理状态
                            String statusCode = tmpBkReader.getFirstTextNotNull("/FOX/SECURITIES_MSGSRSV1/EBIMPAWNTRNRS/STATUS/CODE");
                            String statusMessage = tmpBkReader.getFirstTextNotNull("/FOX/SECURITIES_MSGSRSV1/EBIMPAWNTRNRS/STATUS/MESSAGE");
                            retAtsDetail.ReqSeqID = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBIMPAWNTRNRS/TRNUID");
                            retAtsDetail.RespCode = "0";
                            if (statusCode != null && "0".equals(statusCode)) {
                                //指令处理状态
                                String xferprcCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBIMPAWNTRNRS/RSBODY/XFERPRCSTS/XFERPRCCODE");
                                String xferprcMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBIMPAWNTRNRS/RSBODY/XFERPRCSTS/MESSAGE");
                                retAtsDetail.ReqSeqID = req_b302.detail.ReqSeqID;
                                retAtsDetail.RespInfo = StringHelper.joinNotEmpty("-", statusMessage, xferprcMessage);
                                retAtsDetail.TransState = xferprcCode;
                                retAtsDetail.PayInfoCode = retAtsDetail.TransState;
                            } else {
                                retAtsDetail.RespInfo = statusMessage;
                                retAtsDetail.ReqSeqID = req_b302.detail.ReqSeqID;
                                retAtsDetail.TransState = statusCode;
                                retAtsDetail.PayInfoCode = retAtsDetail.TransState;
                            }
                        } else {
                            retAtsDetail.RespCode = "-1";
                            retAtsDetail.RespInfo = trspmsg;
                        }
                        retAts.wirteRetDetail(retAtsDetail);
                    } else {
                        errorMsg.append(req_b302.detail.BillNum).append(":入池质押报错，").append(tmpSbMsg.toString()).append("\r\n");
                    }
                } else {
                    errorMsg.append(req_b302.detail.BillNum).append(":入池质押报错，").append(tmpRetBkStr[1]).append("\r\n");
                }
            }
        } catch (Exception e) {
            retAts.RespCode = "-1";
            errorMsg.append("入池质押申请出现异常，详情查看DSP日志！").append("\r\n");
            WriteBankLogLn("入池质押申请出现异常:" + e.getMessage());
        } finally {
            conn.close();
            if (errorMsg.length() > 0) {
                WriteBankLogLn(errorMsg.toString());
                if (!"-1".equals(retAts.RespCode)) {
                    retAts.RespCode = "0";
                }
                retAts.RespInfo = errorMsg.toString();
            }
        }
        if (errorMsg.length() == 0) {
            retAts.RespInfo = "处理成功";
        }
        retAts.writeRetAtsXml(retAts);
        return retAts;
    }


    @Override
    public RetAtsB304ImPledge BP102_ImPledge(ReqB304Impledge query) throws Exception {
        return null;
    }

    //票据池处理结果查询
    //此接口用于查询以下业务处理进度：
    // 票据入池
    //  票据出池
    //  质押转托管
    //  托管转质押
    //  出票申请
    //  贴现申请
    //  保证金提取
    //  融资申请
    @Override
    public RetAtsB305DealStateQry BP002_DealStateQry(ReqB305DealStateQry req_b305) throws Exception {
        RetAtsB305DealStateQry retAts = new RetAtsB305DealStateQry(req_b305.reqHeader);
        RetAtsB305DealStateQry errRetAts = new RetAtsB305DealStateQry(req_b305.reqHeader);//出现出错时返回，respcode="-1",不会有明细节点出现
        XmlTextWriter xmlWriter = new XmlTextWriter();
        try {
            writeCommonBillPoolHeaderEn(xmlWriter);
            xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
            xmlWriter.writeStartElement("EBPBILLPOOLRESULTQUERYTRNRQ");
            xmlWriter.writeElementString("TRNUID", req_b305.reqHeader.transSeqID);//客户端交易的唯一流水号 建议值为YYYYMMDD + 序号，最长30位
            xmlWriter.writeStartElement("RQBODY");
            xmlWriter.writeElementString("RELATETRNUID", req_b305.Relatetrnuid);//指令相关流水号，申请时的ReqSeqID
            xmlWriter.writeEndDocument();

            String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString(), req_b305.reqHeader.transType, req_b305.reqHeader.transType);
//            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
//            String[] tmpRetBkStr = {"", "<FOX>\n" +
//                    "    <SIGNONMSGSRSV1>\n" +
//                    "        <SONRS>\n" +
//                    "            <STATUS>\n" +
//                    "                <CODE>0</CODE>\n" +
//                    "                <SEVERITY>INFO</SEVERITY>\n" +
//                    "            </STATUS>\n" +
//                    "            <DTSERVER>2016-08-01 15:56:15</DTSERVER>\n" +
//                    "        </SONRS>\n" +
//                    "    </SIGNONMSGSRSV1>\n" +
//                    "    <SECURITIES_MSGSRSV1>\n" +
//                    "        <EBPBILLPOOLQUERYTRNRS>\n" +
//                    "            <TRNUID>20160722_billPoolResult_01</TRNUID>\n" +
//                    "            <STATUS>\n" +
//                    "                <CODE>0</CODE>\n" +
//                    "                <SEVERITY>INFO</SEVERITY>\n" +
//                    "                <MESSAGE>查询成功!</MESSAGE>\n" +
//                    "            </STATUS>\n" +
//                    "            <RSBODY>\n" +
//                    "                <CONTENT>\n" +
//                    "                    <INDX>1</INDX>\n" +
//                    "                    <STATUS>00</STATUS>\n" +
//                    "                </CONTENT>\n" +
//                    "            </RSBODY>\n" +
//                    "        </EBPBILLPOOLQUERYTRNRS>\n" +
//                    "    </SECURITIES_MSGSRSV1>\n" +
//                    "</FOX>"};

            if (tmpRetBkStr[0].length() == 0) {
                String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                if (tmpBkReader != null) {
                    //响应结果
                    String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                    String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/MESSAGE");
                    if ("0".equals(trspcod)) {
                        //处理状态
                        String statusCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBILLPOOLRESULTQUERYTRNRS/STATUS/CODE");
                        String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBILLPOOLRESULTQUERYTRNRS/STATUS/MESSAGE");
                        if (statusCode != null && statusCode.equals("0")) {
                            retAts.respCode = "0";
                            retAts.respInfo = statusMessage;
                            retAts.relatetrnuid = req_b305.Relatetrnuid;
                            retAts.writeBeforeDetail();
                            while (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBPBILLPOOLRESULTQUERYTRNRS/RSBODY/CONTENT")) {
                                RetAtsB305DealStateQryDetail reAtsDetail = new RetAtsB305DealStateQryDetail();
                                XElement readXElement = tmpBkReader.readedXElement;// 创建读取返回报文的对象
                                reAtsDetail.indx = readXElement.getSingleTextNotNull("INDX");
                                reAtsDetail.billcode = readXElement.getSingleTextNotNull("BILLCODE");//票据号码
                                reAtsDetail.state = readXElement.getSingleTextNotNull("STATUS");//00-未处理 01-处理中 02-已处理 03-已驳回 04-处理失败
                                reAtsDetail.msg = readXElement.getSingleTextNotNull("MSG");//处理信息
                                retAts.writeRetDetail(reAtsDetail);
                            }
                        } else {
                            errRetAts.respCode = "-1";
                            errRetAts.respInfo = statusMessage;
                        }
                    } else {
                        errRetAts.respCode = "-1";
                        errRetAts.respInfo = trspmsg;
                    }
                } else {
                    errRetAts.respCode = "-1";
                    errRetAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                errRetAts.respCode = "-1";
                errRetAts.respInfo = tmpRetBkStr[1];
            }

        } catch (Exception e) {
            errRetAts.respCode = "-1";
            errRetAts.respInfo = "票据池处理结果查询出现异常，详情请查看日志！";
            WriteBankLogLn("票据池处理结果查询出现异常,异常信息:" + e.getMessage());

        }
        if (!StringHelper.isNullOrEmpty(errRetAts.respCode) && errRetAts.respCode.equals("-1")) {
            errRetAts.writeBeforeDetail();
            errRetAts.writeAfterDetail();
            return errRetAts;
        }
        retAts.writeAfterDetail();
        return retAts;
    }


    /**
     * 额度信息查询
     * @param req_b306
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB306PoolAmountQry BP003_PoolAmountQry(ReqB306PoolAmountQry req_b306) throws Exception {
        RetAtsB306PoolAmountQry retAts = new RetAtsB306PoolAmountQry(req_b306.reqHeader);
        retAts.writeStart();
        StringBuilder tmpRespInfo = new StringBuilder();
        List<String> membernameList = new ArrayList<String>();
        while (req_b306.readRecord()) {
            membernameList.add(req_b306.reqDetail.membername);
        }
        int tatalcount = 0;
        try {
            boolean key = true;
            for (int i = 0; i < membernameList.size() || key; i++) {
                if (membernameList.size() == 0 || i == membernameList.size() - 1) {
                    key = false;

                }
                //分页查询
                int page = 1;
                boolean more = true;
                while (more) {
                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    writeCommonBillPoolHeaderEn(xmlWriter);
                    xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
                    xmlWriter.writeStartElement("EBPMEMBERLIMITQUERYTRNRQ");
                    String trnuid = Format.Date8Format.format(new Date()) + getINDX();
                    xmlWriter.writeElementString("TRNUID", trnuid);//客户端交易的唯一流水号 建议值为YYYYMMDD + 序号，最长30位
                    xmlWriter.writeElementAttribute("RQBODY", "PAGE", page + "");
                    xmlWriter.writeElementString("GROUPBILLPOOLNO", req_b306.croupbillpoolno);//集团票据池编号 必填
                    if (req_b306.isGroup.equals("0")) {
                        xmlWriter.writeElementString("MEMBERNAME", "");//成员单位客户名称
                    } else {
                        xmlWriter.writeElementString("MEMBERNAME", membernameList.get(i));//成员单位客户名称
                    }
                    xmlWriter.writeEndDocument();

                    String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString());

                    if (tmpRetBkStr[0].length() == 0) {
                        String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                        if (tmpBkReader != null) {
                            //响应结果
                            String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                            String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/MESSAGE");
                            if ("0".equals(trspcod)) {
                                //处理状态
                                String statusCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPMEMBERLIMITQUERYTRNRS/STATUS/CODE");
                                String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPMEMBERLIMITQUERYTRNRS/STATUS/MESSAGE");
                                if (statusCode != null && statusCode.equals("0")) {
                                    if (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBPMEMBERLIMITQUERYTRNRS/RSBODY")) {
                                        String moreStr = tmpBkReader.readedXElement.getAttrValue("MORE");
                                        if (StringHelper.hasAnyChar(moreStr) && moreStr.equals("Y")) {
                                            more = true;
                                            page++;
                                        } else {
                                            more = false;
                                        }
                                    } else {
                                        tmpRespInfo.append("成员客户名称：" + membernameList.get(i) + "，RSBODY解析出错");
                                        break;
                                    }
                                    tmpBkReader.resetReadMode(XmlReadMode.None);
                                    retAts.respCode = "0";
                                    retAts.respInfo = statusMessage;
                                    tatalcount += Integer.parseInt(tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPMEMBERLIMITQUERYTRNRS/RSBODY/TOTALCOUNT"));
                                    while (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBPMEMBERLIMITQUERYTRNRS/RSBODY/CONTENT")) {
                                        RetAtsB306PoolAmountQryDetail reAtsDetail = new RetAtsB306PoolAmountQryDetail();
                                        XElement readXElement = tmpBkReader.readedXElement;// 创建读取返回报文的对象
                                        reAtsDetail.RespCode = "0";
                                        reAtsDetail.Custname = readXElement.getSingleTextNotNull("CUSTNAME");
                                        reAtsDetail.Contractno = readXElement.getSingleTextNotNull("CONTRACTNO");
                                        reAtsDetail.Contractdate = readXElement.getSingleTextNotNull("CONTRACTDATE");
                                        reAtsDetail.Signorgno = readXElement.getSingleTextNotNull("SIGNORGNO");
                                        reAtsDetail.Signorgname = readXElement.getSingleTextNotNull("SIGNORGNAME");
                                        reAtsDetail.Signdate = readXElement.getSingleTextNotNull("SIGNDATE");
                                        reAtsDetail.Billpoolstatus = readXElement.getSingleTextNotNull("BILLPOOLSTATUS");
                                        reAtsDetail.Bailacctno = readXElement.getSingleTextNotNull("BAILACCTNO");
                                        reAtsDetail.Grpcid = readXElement.getSingleTextNotNull("GRPCID");
                                        reAtsDetail.Grpbillpoolno = readXElement.getSingleTextNotNull("GRPBILLPOOLNO");
                                        reAtsDetail.Grpname = readXElement.getSingleTextNotNull("GRPNAME");
                                        reAtsDetail.Joingrpdate = readXElement.getSingleTextNotNull("JOINGRPDATE");
                                        reAtsDetail.Billremains = readXElement.getSingleTextNotNull("BILLREMAINS");
                                        reAtsDetail.Bailremains = readXElement.getSingleTextNotNull("BAILREMAINS");
                                        reAtsDetail.Billpoollimit = readXElement.getSingleTextNotNull("BILLPOOLLIMIT");
                                        reAtsDetail.Lowrisklimit = readXElement.getSingleTextNotNull("LOWRISKLIMIT");
                                        reAtsDetail.Inlowrisklimit = readXElement.getSingleTextNotNull("INLOWRISKLIMIT");
                                        reAtsDetail.Usedlimit = readXElement.getSingleTextNotNull("USEDLIMIT");
                                        reAtsDetail.Usedlowrisklimit = readXElement.getSingleTextNotNull("USEDLOWRISKLIMIT");
                                        reAtsDetail.Usedinlowrisklimit = readXElement.getSingleTextNotNull("USEDINLOWRISKLIMIT");
                                        if (!StringHelper.isNullOrEmpty(reAtsDetail.Billpoollimit) && !StringHelper.isNullOrEmpty(reAtsDetail.Usedlimit)) {
                                            reAtsDetail.Availablelimit = Double.toString(Double.parseDouble(reAtsDetail.Billpoollimit) - Double.parseDouble(reAtsDetail.Usedlimit));
                                        }
                                        retAts.writeRetDetail(reAtsDetail);
                                    }
                                } else {
                                    tmpRespInfo.append("成员客户名称：" + membernameList.get(i) + "，" + statusMessage);
                                    break;
                                }
                            } else {
                                tmpRespInfo.append("成员客户名称：" + membernameList.get(i) + "，" + trspmsg);
                                break;
                            }
                        } else {
                            tmpRespInfo.append("成员客户名称：" + membernameList.get(i) + "，" + tmpSbMsg.toString());
                            break;
                        }
                    } else {
                        tmpRespInfo.append("成员客户名称：" + membernameList.get(i) + "，" + tmpRetBkStr[1]);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            tmpRespInfo.append("成员单位票据池额度信息查询出现异常");
            WriteBankLogLn("成员单位票据池额度信息查询出现异常,异常信息:" + e.getMessage());
        }
        retAts.tatalcount = tatalcount + "";

        if (tmpRespInfo.length() > 0) {
            retAts.respInfo = tmpRespInfo.toString();
        }
        retAts.writeBeforeDetail();
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsB307PoolAmountAdjust BP103_PoolAmountAdjust(ReqB307PoolAmountAdjust query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB308PoolAmonutAdustQry BP004_AdjustQry(ReqB308PoolAmountAdjustQry query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB309BillApply BP104_BillApply(ReqB309BillApply query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB310ShortLoan BP105_ShortLoan(ReqB310ShortLoan query) throws Exception {
        return null;
    }

    /**
     * 在池票据登记簿（票据明细查询）
     * @param req_b324
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsB324InPoolRegister BP009_InPoolRegister(ReqB324InPoolRegister req_b324) throws Exception {
        RetAtsB324InPoolRegister retAts = new RetAtsB324InPoolRegister(req_b324.reqHeader);
        retAts.writeStart();
        StringBuilder errorMsg = new StringBuilder();
        int totalCount = 0;//票据总数
        Double totalamt = 0.00;//票据总金额
        try {
            if ("0".equals(req_b324.IsPoolQry)) {
                List<String> outintypeList = new ArrayList<String>();
                if (StringHelper.isNullOrEmpty(req_b324.Outintype)) {
                    outintypeList.add("01");
                    outintypeList.add("02");
                } else {
                    outintypeList.add(req_b324.Outintype);
                }
                for (int i = 0; i < outintypeList.size(); i++) {
                    String outintypeStr = outintypeList.get(i).equals("01") ? "托管" : "质押";
                    WriteBankLogLn("开始查询入池方式为" + outintypeStr + "的票据信息....");
                    //兴业银行 查询的交易起始和终止日期必填，但ATS目前又不上送这两个字段，所以DSP默认处理查询当前日期到两年前
                    //兴业银行查询日期范围又不能超过一年
                    Calendar tmpCalendarFrom = Calendar.getInstance();//查询起始日期
                    Calendar tmpCalendarTo = Calendar.getInstance();//查询终止日期
                    if (StringHelper.isNullOrEmpty(req_b324.EndDate)) {
                        tmpCalendarTo.setTime(new Date());
                    } else {
                        tmpCalendarTo.setTime(req_b324.getEndDate());
                    }

                    if (StringHelper.isNullOrEmpty(req_b324.BeginDate)) {
                        tmpCalendarFrom.setTime(tmpCalendarTo.getTime());
                        tmpCalendarFrom.add(Calendar.YEAR, -2);//减2年
                    } else {
                        tmpCalendarFrom.setTime(req_b324.getBeginDate());
                    }

                    int tmpIntDateFrom = 0;
                    int tmpIntDateTo = 1;
                    while (tmpIntDateFrom <= tmpIntDateTo) {

                        Calendar tmpClndrStepTo = Calendar.getInstance();
                        tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                        tmpClndrStepTo.add(Calendar.YEAR, 1);
                        if (tmpCalendarTo.before(tmpClndrStepTo)) {
                            tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                        }

                        WriteBankLogLn("开始查询" + Format.Date10Format.format(tmpCalendarFrom.getTime()) + "-" + Format.Date10Format.format(tmpClndrStepTo.getTime()) + "时间段...");
                        //整池查询
                        int page = 1;
                        boolean more = true;
                        while (more) {
                            more = false;
                            XmlTextWriter xmlWriter = new XmlTextWriter();
                            writeCommonBillPoolHeaderEn(xmlWriter);
                            xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
                            xmlWriter.writeStartElement("EBPINPOOLBILLREGISTERTRNRQ");
                            xmlWriter.writeElementString("TRNUID", req_b324.reqHeader.transSeqID);//客户端交易的唯一流水号 建议值为YYYYMMDD + 序号，最长30位
                            xmlWriter.writeElementAttribute("RQBODY", "PAGE", page + "");
                            xmlWriter.writeElementString("BEGINDATE", Format.Date10Format.format(tmpCalendarFrom.getTime()));//交易起始日期，YYYY-MM-DD
                            xmlWriter.writeElementString("DUEDATE", Format.Date10Format.format(tmpClndrStepTo.getTime()));//交易终止日期, YYYY-MM-DD
                            xmlWriter.writeElementString("BILLMEDIUM", req_b324.Billmedium);//票据介质 1-纸票  2-电票
                            if (StringHelper.isNullOrEmpty(req_b324.BillType)) {
                                xmlWriter.writeElementString("BILLTYPE", "");//票据类型 AC01-银承  AC02-商承
                            } else {
                                xmlWriter.writeElementString("BILLTYPE", "1".equals(req_b324.BillType) ? "AC01" : "AC02");//票据类型 AC01-银承  AC02-商承
                            }
                            xmlWriter.writeElementString("OUTINTYPE", outintypeList.get(i));//入池方式，01-托管   02-质押
                            xmlWriter.writeElementString("BILLCODE", "");//票据号码
                            xmlWriter.writeElementString("BILLSTATUS", req_b324.Billstatus);//票据状态，00-在库  01-托收在途
                            xmlWriter.writeEndDocument();

                            String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString(), req_b324.reqHeader.transType, req_b324.reqHeader.transType);
                            if (tmpRetBkStr[0].length() == 0) {
                                String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                                StringBuilder tmpSbMsg = new StringBuilder();
                                XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                                if (tmpBkReader != null) {
                                    //响应结果
                                    String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                                    String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/MESSAGE");
                                    if ("0".equals(trspcod)) {
                                        //处理状态
                                        String statusCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPINPOOLBILLREGISTERTRNRS/STATUS/CODE");
                                        String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPINPOOLBILLREGISTERTRNRS/STATUS/MESSAGE");
                                        if (statusCode.equals("0")) {
                                            if (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBPINPOOLBILLREGISTERTRNRS/RSBODY")) {
                                                String moreStr = tmpBkReader.readedXElement.getAttrValue("MORE");
                                                if (StringHelper.hasAnyChar(moreStr) && moreStr.equals("Y")) {
                                                    more = true;
                                                    page++;
                                                } else {
                                                    more = false;
                                                }
                                            } else {
                                                retAts.respCode = "-1";
                                                retAts.respInfo = "RSBODY解析出错";
                                                break;
                                            }
                                            tmpBkReader.resetReadMode(XmlReadMode.None);
                                            retAts.respCode = "0";
                                            retAts.respInfo = statusMessage;
                                            String totalCountStr = tmpBkReader.getFirstTextNotNull("/FOX/SECURITIES_MSGSRSV1/EBPINPOOLBILLREGISTERTRNRS/RSBODY/TOTALCOUNT");
                                            totalCount += StringHelper.changeStrToNum(totalCountStr);
                                            String totalamtStr = tmpBkReader.getFirstTextNotNull("/FOX/SECURITIES_MSGSRSV1/EBPINPOOLBILLREGISTERTRNRS/RSBODY/TOTALAMT");
                                            totalamt += Double.parseDouble(totalamtStr);
                                            while (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBPINPOOLBILLREGISTERTRNRS/RSBODY/CONTENT")) {
                                                RetAtsB324InPoolRegisterDetail reAtsDetail = new RetAtsB324InPoolRegisterDetail();
                                                XElement readXElement = tmpBkReader.readedXElement;// 创建读取返回报文的对象
                                                reAtsDetail.Custname = readXElement.getSingleTextNotNull("CUSTNAME");
                                                reAtsDetail.Inpooltype = readXElement.getSingleTextNotNull("OUTINTYPE");
                                                reAtsDetail.Billcode = readXElement.getSingleTextNotNull("BILLCODE");
                                                reAtsDetail.Billamt = readXElement.getSingleTextNotNull("BILLAMT");
                                                reAtsDetail.Billmedium = readXElement.getSingleTextNotNull("BILLMEDIUM");
                                                String BillType = readXElement.getSingleTextNotNull("BILLTYPE");//票据类型
                                                if (!StringHelper.isNullOrEmpty(BillType)) {
                                                    //AC01 银承   AC02 商承
                                                    BillType = BillType.equals("AC01") ? "1" : "2";
                                                }
                                                reAtsDetail.Billtype = BillType;
                                                reAtsDetail.Outdate = readXElement.getSingleTextNotNull("OUTDATE");
                                                reAtsDetail.Duedate = readXElement.getSingleTextNotNull("DUEDATE");
                                                reAtsDetail.Drawername = readXElement.getSingleTextNotNull("DRAWERNAME");
                                                reAtsDetail.Deaweracctno = readXElement.getSingleTextNotNull("DRAWERACCTNO");
                                                reAtsDetail.Payeename = readXElement.getSingleTextNotNull("PAYEENAME");
                                                reAtsDetail.Payeeacctno = readXElement.getSingleTextNotNull("PAYEEACCTNO");
                                                reAtsDetail.Payeebankname = readXElement.getSingleTextNotNull("PAYEEBANKNAME");
                                                reAtsDetail.Payeebankcode = readXElement.getSingleTextNotNull("PAYEEBANKCODE");
                                                reAtsDetail.AcceptbankName = readXElement.getSingleTextNotNull("ACCEPTBANK");
                                                reAtsDetail.Drawerbankname = readXElement.getSingleTextNotNull("DRAWERBANKNAME");
                                                reAtsDetail.Drawerbankcode = readXElement.getSingleTextNotNull("DRAWERBANKCODE");
                                                reAtsDetail.Bailcontractno = readXElement.getSingleTextNotNull("BAILCONTRACTNO");
                                                reAtsDetail.Tradedate = readXElement.getSingleTextNotNull("TRADEDATE");
                                                reAtsDetail.Loantovalueratio = readXElement.getSingleTextNotNull("LOANTOVALUERATIO");
                                                reAtsDetail.Billstatus = readXElement.getSingleTextNotNull("BILLSTATUS");
                                                reAtsDetail.Belongorgno = readXElement.getSingleTextNotNull("BELONGORGNO");
                                                reAtsDetail.Belongrorgname = readXElement.getSingleTextNotNull("BELONGORGNAME");
                                                retAts.writeRetDetail(reAtsDetail);
                                            }
                                        } else {
                                            retAts.respCode = "0";
                                            errorMsg.append("查询入池方式:").append(outintypeStr).append(Format.Date10Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date10Format.format(tmpClndrStepTo.getTime())).append("时间段查询报错：").append(statusMessage).append("\r\n");
                                        }
                                    } else {
                                        retAts.respCode = "0";
                                        errorMsg.append("查询入池方式:").append(outintypeStr).append(Format.Date10Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date10Format.format(tmpClndrStepTo.getTime())).append("时间段查询报错：").append(trspmsg).append("\r\n");
                                    }
                                } else {
                                    retAts.respCode = "0";
                                    errorMsg.append("查询入池方式:").append(outintypeStr).append(Format.Date10Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date10Format.format(tmpClndrStepTo.getTime())).append("时间段查询报错：").append(tmpSbMsg.toString()).append("\r\n");
                                }
                            } else {
                                retAts.respCode = "0";
                                errorMsg.append("查询入池方式:").append(outintypeStr).append(Format.Date10Format.format(tmpCalendarFrom.getTime())).append("到").append(Format.Date10Format.format(tmpClndrStepTo.getTime())).append("时间段查询报错：").append(tmpRetBkStr[1]).append("\r\n");
                            }
                        }
                        tmpClndrStepTo.add(Calendar.DATE, 1);
                        tmpCalendarFrom = tmpClndrStepTo;
                        tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                        tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                    }
                }
            } else {
                retAts.respCode = "-1";
                errorMsg.append("兴业银行票据池只支持整池查询").append("\r\n");
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            errorMsg.append("在池票据登记簿出现异常，详情请查看日志！").append("\r\n");
            WriteBankLogLn("在池票据登记簿出现异常,异常信息:" + e.getMessage());
        } finally {
            if (errorMsg.length() > 0) {
                WriteBankLogLn(errorMsg.toString());
            }
        }
        if (errorMsg.length() > 0) {
            retAts.respInfo = errorMsg.toString();
        } else {
            retAts.respInfo = "处理成功！";
        }
        retAts.totalamt = totalamt.toString();
        retAts.tatalcount = totalCount + "";
        retAts.writeBeforeDetail();
        retAts.writeEnd();
        return retAts;
    }


    /**
     * 通用撤回请求
     * @param query
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBP108BillCancSubmit BP108_BillWithdrawalReq(ReqBP108BillCancSubmit query) throws Exception {
        RetAtsBP108BillCancSubmit retAts = new RetAtsBP108BillCancSubmit(query.reqHeader);
        retAts.writeBeforeDetail();
        Connection conn = FGBiz.getLocalDbConn();
        while (query.readRecord()) {
            RetAtsBP108BillCancSubmitDetail detail = new RetAtsBP108BillCancSubmitDetail();
            String[] busiNo = query.detail.busiNo.split("@");
            try {
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeaderEn(xmlWriter, "encoding=\"gb2312\"");
//                <SECURITIES_MSGSRQV1>	请求服务指令消息集	必输
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
//                        <EBRECEDETRNRQ>	服务标识	必输
                xmlWriter.writeStartElement("EBRECEDETRNRQ");
//                <TRNUID/>	客户端交易的唯一流水号
//                建议值为YYYYMMDD+序号，最长30位	必输
                String trnuId = getQryTransID();
                xmlWriter.writeElementString("TRNUID", trnuId);
//                <RQBODY>	消息报文体	非必输
                xmlWriter.writeStartElement("RQBODY");
//                        <TOTALCOUNT/>	票据总笔数,8位整数	必输
                xmlWriter.writeElementString("TOTALCOUNT", "1");
//                <TOTALAMT/>	票据总金额,17位(15整数位,2小数位) 	必输
                xmlWriter.writeElementString("TOTALAMT", query.detail.billAmt);
//                        <ACCTID/>	业务撤回申请人账户代号,最大32位	必输
                xmlWriter.writeElementString("ACCTID", query.detail.actNum);
//                        <CONTENT>	票据内容循环体，最多100条	必输
                xmlWriter.writeStartElement("CONTENT");
//                <INDX/>	小序号,4位	必输
                xmlWriter.writeElementString("INDX", "0001");
//                <BILLCODE/>	票据号码,30位	必输
                xmlWriter.writeElementString("BILLCODE", query.detail.billNo);
//                <BILLAMT/>	票据金额,17位(15整数位,2小数位)	必输
                xmlWriter.writeElementString("BILLAMT", query.detail.billAmt);
//                        <BUSINESSTYPE/>	业务标识码,2位,见:附录3-业务类型对照表	必输
                //    撤回类型 1-承兑申请撤回 2-提示收票申请撤回 3-背书转让申请撤回 4-贴现申请撤回 5-质押申请撤回 6-（逾期）提示付款撤回
//    7-出票保证申请撤回 8-承兑保证申请撤回  9-背书保证申请撤回 10-追索通知撤回 11-同意清偿撤回 12-解质押申请撤回
                String cancelType;
                switch (Integer.valueOf(query.detail.cancelType)) {
                    case 1:
                        cancelType = "22";
                        break;
                    case 2:
                        cancelType = "23";
                        break;
                    case 3:
                        cancelType = "24";
                        break;
                    case 4:
                        cancelType = "25";
                        break;
                    case 5:
                        cancelType = "33";
                        break;
                    case 6:
                        cancelType = "35";
                        break;
                    case 7:
                        cancelType = "32";
                        break;
                    case 8:
                        cancelType = "31";
                        break;
                    case 9:
                        cancelType = "30";
                        break;
                    case 10:
                        cancelType = "38";
                        break;
                    case 11:
                        cancelType = "37";
                        break;
                    case 12:
                        cancelType = "34";
                        break;
                    default:
                        throw new Exception("撤回类型未知：" + query.detail.cancelType);
                }
                xmlWriter.writeElementString("BUSINESSTYPE", cancelType);
//                        <BIZFLAG/>	业务标识号,1-35位	必输
                xmlWriter.writeElementString("BIZFLAG", busiNo[1]);
//                <SEQ/>	业务流水号(可操作票据查询返回),1-20位	必输
                xmlWriter.writeElementString("SEQ", busiNo[0]);
//                <APPDATE/>	撤回申请日期,YYYY-MM-DD	必输
                xmlWriter.writeElementString("APPDATE", Format.Date10Format.format(new Date()));
//                        </CONTENT>
//                </RQBODY>
//                </EBRECEDETRNRQ>
//                </SECURITIES_MSGSRQV1>


                xmlWriter.writeEndDocument();
                String xmlSend = writeContentLength(xmlWriter);
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                JDBCHelper.update(conn, INSERTRECEIPT2, new Object[]{uuid, query.reqHeader.bankCode, "EBRECEDETRNRQ", Format.Date8Format.format(new Date()), query.detail.reqSeqID, trnuId});
                String[] result = sendToBank(xmlSend);
                if (result[0].length() == 0) {
                    String returnXml = result[1].substring(result[1].indexOf("<FOX>"), result[1].length());
                    StringBuilder tmpSbmsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbmsg);
                    if (tmpBkReader != null) {
                        String code = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBRECEDETRNRS/STATUS/CODE");
                        if ("0".equals(code)) {
                            detail.respCode = "0";
                            detail.respInfo = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBRECEDETRNRS/RSBODY/XFERPRCSTS/MESSAGE");
                            detail.transState = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBRECEDETRNRS/RSBODY/XFERPRCSTS/XFERPRCCODE");
                            detail.payInfoCode = detail.transState;
                            detail.reqSeqID = query.detail.reqSeqID;
                        } else {
                            detail.respCode = "0";
                            detail.respInfo = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBRECEDETRNRS/STATUS/MESSAGE");
                            detail.transState = code;
                            detail.payInfoCode = detail.transState;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSbmsg.toString();
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = result[1];
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                detail.respCode = "-1";
                detail.respInfo = ex.getMessage();
            } finally {
                conn.close();
            }
            retAts.writeDetail(detail);
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 通用签收/拒签请求（电票B003和票据池通用一个银行接口一个改都需要改）
     * @param query
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsBP109BillRespSubmit BP109_BillPublicrReply(ReqBP109BillRespSubmit query) throws Exception {
        RetAtsBP109BillRespSubmit retAts = new RetAtsBP109BillRespSubmit(query.reqHeader);
        retAts.writeBeforeDetail();
        Connection conn = FGBiz.getLocalDbConn();
        while (query.readRecord()) {
            RetAtsBP109BillRespSubmitDetail detail = new RetAtsBP109BillRespSubmitDetail();
            try {
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeaderEn(xmlWriter, "encoding=\"gb2312\"");
//<SECURITIES_MSGSRQV1>	请求服务指令消息集	必输
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
//                <EBSIGNTRNRQ>	服务标识	必输
                xmlWriter.writeStartElement("EBSIGNTRNRQ");
//                        <TRNUID/>	客户端交易的唯一流水号
                String trnuId = getQryTransID();
                xmlWriter.writeElementString("TRNUID", trnuId);
//                建议值为YYYYMMDD+序号，最长30位	必输
//                <RQBODY>	消息报文体	非必输
                xmlWriter.writeStartElement("RQBODY");
//                        <TOTALCOUNT/>	票据总笔数,8位整数	必输
                xmlWriter.writeElementString("TOTALCOUNT", "1");
//                <TOTALAMT/>	票据总金额,17位(15整数位,2小数位) 	必输
                xmlWriter.writeElementString("TOTALAMT", query.detail.billAmt);
//                        <SIGNDATE/>	签收日期,YYYY-MM-DD	必输
                xmlWriter.writeElementString("SIGNDATE", Format.Date10Format.format(new Date()));
//                        <ACCTID/>	签收人账户代号,最大32位	必输
                xmlWriter.writeElementString("ACCTID", query.detail.actNum);
//                        <SIGNRSLT/>	签收结果,4位
//                        (SU00:同意签收, SU01:拒绝签收)	必输
                String respFlag;
                if ("1".equals(query.detail.respFlag)) {
                    respFlag = "SU00";
                } else {
                    respFlag = "SU01";
                }
                xmlWriter.writeElementString("SIGNRSLT", respFlag);
//                        <RJRSN/>	拒签理由, 4位见附录:拒付理由/拒签理由	非必输
//                N--DC0(N-1) 99--DC09
//                if(StringHelper.hasAnyChar(query.detail.unPayCode)) {
//                    String unPayCode;
//                    int i = Integer.valueOf(query.detail.unPayCode);
//                    if (99 != i) {
//                        unPayCode = "DC0" + (i - 1);
//                    } else {
//                        unPayCode = "DC09";
//                    }
//                    xmlWriter.writeElementString("RJRSN", unPayCode);
//                }
                Set<String> respTypeSet = new LinkedHashSet<String>();
                respTypeSet.add("1");   //承兑应答
                respTypeSet.add("2");   //收票应答
                respTypeSet.add("3");   //背书转让应答
                respTypeSet.add("4");   //回购式贴现赎回应答
                respTypeSet.add("5");   //质押解除应答
                respTypeSet.add("7");   //保证应答
                respTypeSet.add("8");   //同意清偿应答
                respTypeSet.add("9");   //质押签收
                respTypeSet.add("10");  //贴现签收
                if ("SU01".equals(respFlag)) {
                    if (respTypeSet.contains(query.detail.respType)) {
                        xmlWriter.writeElementString("RJRSN", "DC09");
//                  <RJMEMO/>	拒签备注,最大256位，兴业银行签收拒绝时，拒绝理由为必输，和客户及银行沟通后理由填其它
                        xmlWriter.writeElementString("RJMEMO", "不符合要求");
                    } else {
                        if (StringHelper.hasAnyChar(query.detail.unPayCode)) {
                            String unPayCode;
                            int i = Integer.valueOf(query.detail.unPayCode);
                            if (99 != i) {
                                unPayCode = "DC0" + (i - 1);
                            } else {
                                unPayCode = "DC09";
                            }
                            xmlWriter.writeElementString("RJRSN", unPayCode);
//                        <RJMEMO/>	拒签备注,最大256位	非必输
                            xmlWriter.writeElementString("RJMEMO", query.detail.unPayMemo);
                        }
                    }
                }
//                        <SIGNMEMO/>	签收人备注,最大256位	非必输
                xmlWriter.writeElementString("SIGNMEMO", query.detail.memo);
//                        <CONTENT>	票据内容循环体	必输
                xmlWriter.writeStartElement("CONTENT");
//                <INDX/>	小序号,4位	必输
                xmlWriter.writeElementString("INDX", "0001");
//                <BILLCODE/>	票据号码,30位	必输
                xmlWriter.writeElementString("BILLCODE", query.detail.billNo);
//                <BILLAMT/>	票据金额,17位(15整数位,2小数位)	必输
                xmlWriter.writeElementString("BILLAMT", query.detail.billAmt);
//                        <BUSINESSTYPE/>	业务类型,2位,见:附录3-业务类型对照表	必输
                String respType;
                //1-承兑应答 2-收票应答 3-背书转让应答 4-回购式贴现赎回应答 5-质押解除应答 6-提示付款应答
                //7-保证应答 8-同意清偿应,9-质押签收
                switch (Integer.valueOf(query.detail.respType)) {
//                    03  05 07 10 16 17 xx 31
                    case 1:
                        respType = "03";
                        break;
                    case 2:
                        respType = "05";
                        break;
                    case 3:
                        respType = "07";
                        break;
                    case 4:
                        respType = "10";
                        break;
                    case 5:
                        respType = "16";
                        break;
                    case 6:
                        respType = "17";
                        break;
                    case 7:
                        throw new Exception("不明确是出票保证，承兑保证还是背书保证，暂不对接该端口");
                    case 8:
                        respType = "21";
                        break;
                    case 9:
                        respType = "15";
                        break;
                    default:
                        throw new Exception("业务类型未知:" + query.detail.respType);
                }
                xmlWriter.writeElementString("BUSINESSTYPE", respType);
//                <ENTRSPAY/>	到期无条件支付委托,4位只能是CC00	必输
                xmlWriter.writeElementString("ENTRSPAY", "CC00");
//                <AGRM/>	协议号,承兑,贴现时有效,0-30位	非必输
                xmlWriter.writeElementString("AGRM", query.detail.protocolNo);
//                <BIZFLAG/>	业务标识号,最大35位，待签收票据查询中获取	必输
                xmlWriter.writeElementString("BIZFLAG", query.detail.busiNo);
//                </CONTENT>
//                </RQBODY>
//                </EBSIGNTRNRQ>
//                </SECURITIES_MSGSRQV1>
                xmlWriter.writeEndDocument();
                String xmlSend = writeContentLength(xmlWriter);
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                JDBCHelper.update(conn, INSERTRECEIPT2, new Object[]{uuid, query.reqHeader.bankCode, "EBSIGNTRNRQ", Format.Date8Format.format(new Date()), query.detail.reqSeqID, trnuId});
                String[] result = sendToBank(xmlSend);
                if (result[0].length() == 0) {
                    String returnXml = result[1].substring(result[1].indexOf("<FOX>"), result[1].length());
                    StringBuilder tmpSbmsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbmsg);
                    if (tmpBkReader != null) {
                        String code = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBSIGNTRNRS/STATUS/CODE");
                        if ("0".equals(code)) {
                            detail.respCode = "0";
                            detail.respInfo = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBSIGNTRNRS/RSBODY/XFERPRCSTS/MESSAGE");
                            detail.transState = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBSIGNTRNRS/RSBODY/XFERPRCSTS/XFERPRCCODE");
                            detail.payInfoCode = detail.transState;
                            detail.reqSeqID = query.detail.reqSeqID;
                        } else {
                            detail.respCode = "0";
                            detail.respInfo = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBSIGNTRNRS/STATUS/MESSAGE");
                            detail.transState = code;
                            detail.payInfoCode = detail.transState;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSbmsg.toString();
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = result[1];
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                detail.respCode = "-1";
                detail.respInfo = ex.getMessage();
            } finally {
                conn.close();
            }
            retAts.writeDetail(detail);
        }
        retAts.writeEnd();
        return retAts;
    }


    //票据批量状态查询
    //兴业银行票据池和电票B006用的同样的接口，修改的话两个都要修改
    @Override
    public RetAtsBP008BillStateQry BP008_BillState_Qeury(ReqBP008BillStateQry query) throws Exception {
        if (getBankConfig().getValueAsBool("useNewBillStateQry")) {
            return billStateQeuryByNewInterface(query);
        } else {
            return old_BillState_Qry(query);
        }
    }

    public RetAtsBP008BillStateQry billStateQeuryByNewInterface(ReqBP008BillStateQry query) throws Exception {
        RetAtsBP008BillStateQry retAts = new RetAtsBP008BillStateQry(query.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        while (query.readRecord()) {
            RetAtsBP008BillStateQryDetail detail = new RetAtsBP008BillStateQryDetail();
            try {
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeaderEn(xmlWriter, "encoding=\"gb2312\"");
//                    < SECURITIES_MSGSRQV1>		必输
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
//                            <EBILLTRANSRESULTQUERYTRNRQ>		必输
                xmlWriter.writeStartElement("EBILLTRANSRESULTQUERYTRNRQ");
                Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{query.detail.reqSeqID, query.reqHeader.bankCode});
                if (map.size() == 0) {
                    detail.respCode = "-1";
                    detail.respInfo = "没有找到流水号对应的票据ID号！";
                    retAts.writeDetail(detail);
                    retAts.writeEnd();
                    return retAts;
                }
//                            <TRNUID/>	客户端交易的唯一流水号
                xmlWriter.writeElementString("TRNUID", getQryTransID());
//                xmlWriter.writeElementString("TRNUID", srnuId);
//                    建议值为YYYYMMDD+序号，最长30位	必输
//                    <RQBODY PAGE=“1”>	PAGE查询页码，必输
                xmlWriter.writeStartElement("RQBODY");
//                            <ACCTID/>	操作员账户代号,最大32位	必输
//                xmlWriter.writeElementString("ACCTID", query.detail.actNum);
//                    String transDate = map.get("TRANSDATE").toString();
                xmlWriter.writeElementString("CLIENTREF", map.get("BANKREQSEQID").toString());
//                            </RQBODY>
//                    </EBBATCHSTATUSTRNRQ>
//                    </ SECURITIES_MSGSRQV1>
                xmlWriter.writeEndDocument();
                String xmlSend = writeContentLength(xmlWriter);
                String[] result = sendToBank(xmlSend);
                if (result[0].length() == 0) {
                    String returnXml = result[1].substring(result[1].indexOf("<FOX>"));
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBILLTRANSRESULTQUERYTRNRS/STATUS/CODE");
                        String returnMsg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBILLTRANSRESULTQUERYTRNRS/STATUS/MESSAGE");
                        if ("0".equals(returnCode)) {
                            if (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBILLTRANSRESULTQUERYTRNRS/RSBODY")) {
                                ArrayList<XElement> list = tmpBkReader.readedXElement.getChildList("CONTENT");
                                if (list == null || list.size() == 0 || list.size() != 1) {
                                    throw new Exception("返回的记录条数不唯一返回条数为：" + (list != null ? list.size() : "0"));
                                }
                                for (XElement xElement : list) {
                                    detail.respCode = "0";
                                    detail.respInfo = returnMsg;
                                    //电子票据号码
                                    detail.billNo = xElement.getSingleText("BILL_CODE");
                                    //银行交易处理状态码
                                    detail.transState = xElement.getSingleText("TRANS_STATUS");
                                    //银行交易信息码
                                    detail.payInfoCode = detail.transState;
                                    //票据状态
                                    detail.billState = getBillStateByBillNo(detail.billNo, query.detail.actNum);
                                }
                            } else {
                                detail.respCode = "-1";
                                detail.respInfo = "返回的内容没有状态信息";
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = returnMsg;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = result[1];
                }
            } catch (Exception e) {
                detail.respCode = "-1";
                detail.respCode = e.getMessage();
                e.printStackTrace();
            } finally {
                conn.close();
            }
            retAts.writeDetail(detail);
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsBP008BillStateQry old_BillState_Qry(ReqBP008BillStateQry query) throws Exception {
        RetAtsBP008BillStateQry retAts = new RetAtsBP008BillStateQry(query.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        while (query.readRecord()) {
            RetAtsBP008BillStateQryDetail detail = new RetAtsBP008BillStateQryDetail();
            try {
                XmlTextWriter xmlWriter = new XmlTextWriter();
                xmlWriter.autoFormat = false;
                writeCommonHeaderEn(xmlWriter, "encoding=\"gb2312\"");
//                    < SECURITIES_MSGSRQV1>		必输
                xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
//                            <EBBATCHSTATUSTRNRQ>		必输
                xmlWriter.writeStartElement("EBBATCHSTATUSTRNRQ");
//                            <CLIENTREF/>	客户交易流水号
                Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{query.detail.reqSeqID, query.reqHeader.bankCode});
                if (map.size() == 0) {
                    detail.respCode = "0";
                    detail.respInfo = "没有找到银行流水号！";
                    retAts.writeDetail(detail);
                    retAts.writeEnd();
                    return retAts;
                }
//                            <TRNUID/>	客户端交易的唯一流水号
                String srnuId = getQryTransID();
                xmlWriter.writeElementString("TRNUID", map.get("BANKREQSEQID").toString());
//                xmlWriter.writeElementString("TRNUID", srnuId);
//                    建议值为YYYYMMDD+序号，最长30位	必输
//                    <RQBODY PAGE=“1”>	PAGE查询页码，必输
                xmlWriter.writeElementAttribute("RQBODY", "PAGE", "1");
//                            <ACCTID/>	操作员账户代号,最大32位	必输
                xmlWriter.writeElementString("ACCTID", query.detail.actNum);
                String outTransId = map.get("BANKREQSEQID").toString();
//                    String transDate = map.get("TRANSDATE").toString();
                xmlWriter.writeElementString("CLIENTREF", outTransId);
//                            </RQBODY>
//                    </EBBATCHSTATUSTRNRQ>
//                    </ SECURITIES_MSGSRQV1>
                xmlWriter.writeEndDocument();
                String xmlSend = writeContentLength(xmlWriter);
                String[] result = sendToBank(xmlSend);
                if (result[0].length() == 0) {
                    String returnXml = result[1].substring(result[1].indexOf("<FOX>"), result[1].length());
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBBATCHSTATUSTRNRS/STATUS/CODE");
                        String returnMsg = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBBATCHSTATUSTRNRS/STATUS/MESSAGE");
                        if ("0".equals(returnCode)) {
                            if (tmpBkReader.read("/FOX/SECURITIES_MSGSRSV1/EBBATCHSTATUSTRNRS/RSBODY")) {
                                ArrayList<XElement> list = tmpBkReader.readedXElement.getChildList("CONTENT");
                                if (list == null || list.size() == 0 || list.size() != 1) {
                                    throw new Exception("返回的记录条数不唯一返回条数为：" + (list != null ? list.size() : "0"));
                                }
                                for (XElement xElement : list) {
                                    detail.respCode = "0";
                                    detail.respInfo = xElement.getSingleText("RSLTMSG");
                                    //电子票据号码
                                    detail.billNo = xElement.getSingleText("BILLCODE");
                                    //银行交易处理状态码
                                    detail.transState = xElement.getSingleText("RSLTID");
                                    //银行交易信息码
                                    detail.payInfoCode = detail.transState;
                                    //票据状态
                                    detail.billState = xElement.getSingleText("BILLSTATUS");
                                }
                            } else {
                                detail.respCode = "-1";
                                detail.respInfo = "返回的内容没有状态信息";
                            }
                        } else {
                            detail.respCode = "-1";
                            detail.respInfo = returnMsg;
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = result[1];
                }
            } catch (Exception e) {
                detail.respCode = "-1";
                detail.respCode = e.getMessage();
                e.printStackTrace();
            } finally {
                conn.close();
            }
            retAts.writeDetail(detail);
        }
        retAts.writeEnd();
        return retAts;
    }

    //兴业银行保证金提取
    @Override
    public RetAtsB311AssuranceTransmit BP107_AssuranceTransmit(ReqB311AssuranceTransmit req_b312) throws Exception {
        RetAtsB311AssuranceTransmit retAts = new RetAtsB311AssuranceTransmit(req_b312.reqHeader);
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            writeCommonBillPoolHeaderEn(xmlWriter);
            xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
            xmlWriter.writeStartElement("EBPBAILTRNRQ");
            String trnuid = req_b312.ReqSeqID + getINDX();
            xmlWriter.writeElementString("TRNUID", trnuid);//客户端交易的唯一流水号 建议值为YYYYMMDD + 序号，最长30位
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, req_b312.reqHeader.bankCode, req_b312.ReqSeqID, trnuid, ""});
            xmlWriter.writeStartElement("RQBODY");
            xmlWriter.writeElementString("DRAWAMT", req_b312.TransmitAmount);//提取金额（18,2）
            xmlWriter.writeElementString("BAILACCTNO", req_b312.AccountNum);//保证金账户，查询商票签约信息来获取
            xmlWriter.writeElementString("TOACCTNO", req_b312.ToAccountNum);//转入账号
            xmlWriter.writeEndDocument();


            String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString(), req_b312.reqHeader.transType, req_b312.reqHeader.transType);
//            String[] tmpRetBkStr = {"", "<FOX>\n" +
//                    "    <SIGNONMSGSRSV1>\n" +
//                    "        <SONRS>\n" +
//                    "            <STATUS>\n" +
//                    "                <CODE>0</CODE>\n" +
//                    "                <SEVERITY>INFO</SEVERITY>\n" +
//                    "            </STATUS>\n" +
//                    "            <DTSERVER>2016-08-11 14:07:32</DTSERVER>\n" +
//                    "        </SONRS>\n" +
//                    "    </SIGNONMSGSRSV1>\n" +
//                    "    <SECURITIES_MSGSRSV1>\n" +
//                    "        <EBPBAILTRNRS>\n" +
//                    "            <TRNUID>20160801_bail_02</TRNUID>\n" +
//                    "            <STATUS>\n" +
//                    "                <CODE>0</CODE>\n" +
//                    "                <SEVERITY>INFO</SEVERITY>\n" +
//                    "                <MESSAGE>保证金提取指令提交成功!</MESSAGE>\n" +
//                    "            </STATUS>\n" +
//                    "            <RSBODY>\n" +
//                    "                <DRAWAMT>100.00</DRAWAMT>\n" +
//                    "                <XFERPRCSTS>\n" +
//                    "                    <XFERPRCCODE>PAYOUT</XFERPRCCODE>\n" +
//                    "                    <DTXFERPRC>2016-08-11 14:07:32</DTXFERPRC>\n" +
//                    "                    <MESSAGE>交易成功</MESSAGE>\n" +
//                    "                </XFERPRCSTS>\n" +
//                    "            </RSBODY>\n" +
//                    "        </EBPBAILTRNRS>\n" +
//                    "    </SECURITIES_MSGSRSV1>\n" +
//                    "</FOX>"};

            if (tmpRetBkStr[0].length() == 0) {
                String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                if (tmpBkReader != null) {
                    //响应结果
                    String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                    String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/MESSAGE");
                    if ("0".equals(trspcod)) {
                        //交易处理状态
                        String statusCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/STATUS/CODE");
                        String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/STATUS/MESSAGE");
                        //指令处理状态
                        String xferprcCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/RSBODY/XFERPRCSTS/XFERPRCCODE");
                        String xferprcMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/RSBODY/XFERPRCSTS/MESSAGE");
                        retAts.RespCode = "0";
//                        retAts.ReqSeqID = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/TRNUID");
                        retAts.ReqSeqID = req_b312.ReqSeqID;
                        retAts.RespInfo = StringHelper.joinNotEmpty("-", statusMessage, xferprcMessage);
                        retAts.TransState = statusCode + "+" + xferprcCode;
                        retAts.PayInfoCode = retAts.TransState;
                    } else {
                        retAts.RespCode = "-1";
                        retAts.RespInfo = trspmsg;
                    }
                } else {
                    retAts.RespCode = "-1";
                    retAts.RespInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.RespCode = "-1";
                retAts.RespInfo = tmpRetBkStr[1];
            }
        } catch (Exception e) {
            retAts.RespCode = "-1";
            retAts.RespInfo = "保证金提取出现异常！";
            WriteBankLogLn("保证金提取出现异常,异常信息：" + e.getMessage());
        } finally {
            conn.close();
        }
        retAts.writeRetAtsXml(retAts);
        return retAts;
    }

    //保证提取处理结果查询
    @Override
    public RetAtsB311AssuranceTransmit BP007_AssuranceTransmitQry(ReqB329AssuranceTransmitQry req_b329) throws Exception {
        //兴业银行该保证金处理结果查询接口 ，行方回答：“这个查询请求只是查询保证金提取申请是否提交成功”，最终处理结果用票据池处理结果查询（只查询处理进度）
        RetAtsB311AssuranceTransmit retAts = new RetAtsB311AssuranceTransmit(req_b329.reqHeader);
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{req_b329.ReqSeqID, req_b329.reqHeader.bankCode});
            if (map.size() <= 0) {
                retAts.RespCode = "0";
                retAts.RespInfo = "本地没有映射流水号";
                retAts.writeRetAtsXml(retAts);
                return retAts;
            }
            writeCommonBillPoolHeaderEn(xmlWriter);
            xmlWriter.writeStartElement("SECURITIES_MSGSRQV1");
            xmlWriter.writeStartElement("EBPBAILTRNRQ");
            xmlWriter.writeElementString("TRNUID", map.get("BANKREQSEQID").toString());//客户方系统提交请求时的唯一交易流水
            xmlWriter.writeEndDocument();

            String[] tmpRetBkStr = sendToBankReceipt(xmlWriter.toXmlString(), req_b329.reqHeader.transType, req_b329.reqHeader.transType);

            if (tmpRetBkStr[0].length() == 0) {
                String returnXml = tmpRetBkStr[1].substring(tmpRetBkStr[1].indexOf("<FOX>"), tmpRetBkStr[1].length());
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(returnXml, tmpSbMsg);
                if (tmpBkReader != null) {
                    //响应结果
                    String trspcod = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/CODE");
                    String trspmsg = tmpBkReader.getFirstText("/FOX/SIGNONMSGSRSV1/SONRS/STATUS/MESSAGE");
                    if ("0".equals(trspcod)) {
                        //交易处理状态
                        String statusCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/STATUS/CODE");
                        String statusMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/STATUS/MESSAGE");
                        //指令处理状态
                        String xferprcCode = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/RSBODY/XFERPRCSTS/XFERPRCCODE");
                        String xferprcMessage = tmpBkReader.getFirstText("/FOX/SECURITIES_MSGSRSV1/EBPBAILTRNRS/RSBODY/XFERPRCSTS/MESSAGE");
                        retAts.RespCode = "0";
                        retAts.ReqSeqID = req_b329.ReqSeqID;
                        retAts.RespInfo = StringHelper.joinNotEmpty("-", statusMessage, xferprcMessage);
                        retAts.TransState = statusCode + "+" + xferprcCode;
                        retAts.PayInfoCode = retAts.TransState;
                    } else {
                        retAts.RespCode = "-1";
                        retAts.RespInfo = trspmsg;
                    }
                } else {
                    retAts.RespCode = "-1";
                    retAts.RespInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.RespCode = "-1";
                retAts.RespInfo = tmpRetBkStr[1];
            }
        } catch (Exception e) {
            retAts.RespCode = "-1";
            retAts.RespInfo = "保证金提取处理结果查询出现异常！";
            WriteBankLogLn("保证金提取处理结果查询出现异常,异常信息：" + e.getMessage());
        } finally {
            conn.close();
        }
        retAts.writeRetAtsXml(retAts);
        return retAts;
    }

    @Override
    public RetAtsB312AssuranceDetail BP005_AssuracneDetail(ReqB312AssuranceDetail query) throws Exception {
        return null;
    }

    @Override
    public RetAtsB315LoanDetail BP006_LoanDetail(ReqB315LoanDetail query) throws Exception {
        return null;
    }


    @Override
    public RetAtsB311LoanRepay BP106_LoanRepay(ReqB311LoanRepay query) throws Exception {
        return null;
    }


}
